实现由先序序列和中序序列以及由中序序列和后序序列构造一棵二叉树的完整代码包含头文件和main函数
时间: 2023-12-05 08:58:42 浏览: 74
erchashu.zip_二叉树_数据结构
下面是由先序序列和中序序列构造一棵二叉树的代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
if (preorder.empty() || inorder.empty()) {
return NULL;
}
int rootVal = preorder[0];
TreeNode* root = new TreeNode(rootVal);
int inorderRootIndex = 0;
for (int i = 0; i < inorder.size(); i++) {
if (inorder[i] == rootVal) {
inorderRootIndex = i;
break;
}
}
vector<int> leftInorder(inorder.begin(), inorder.begin() + inorderRootIndex);
vector<int> rightInorder(inorder.begin() + inorderRootIndex + 1, inorder.end());
vector<int> leftPreorder(preorder.begin() + 1, preorder.begin() + 1 + leftInorder.size());
vector<int> rightPreorder(preorder.begin() + 1 + leftInorder.size(), preorder.end());
root->left = buildTree(leftPreorder, leftInorder);
root->right = buildTree(rightPreorder, rightInorder);
return root;
}
int main() {
vector<int> preorder = {3, 9, 20, 15, 7};
vector<int> inorder = {9, 3, 15, 20, 7};
TreeNode* root = buildTree(preorder, inorder);
return 0;
}
```
下面是由中序序列和后序序列构造一棵二叉树的代码:
```c++
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
if (inorder.empty() || postorder.empty()) {
return NULL;
}
int rootVal = postorder.back();
TreeNode* root = new TreeNode(rootVal);
int inorderRootIndex = 0;
for (int i = 0; i < inorder.size(); i++) {
if (inorder[i] == rootVal) {
inorderRootIndex = i;
break;
}
}
vector<int> leftInorder(inorder.begin(), inorder.begin() + inorderRootIndex);
vector<int> rightInorder(inorder.begin() + inorderRootIndex + 1, inorder.end());
vector<int> leftPostorder(postorder.begin(), postorder.begin() + leftInorder.size());
vector<int> rightPostorder(postorder.begin() + leftInorder.size(), postorder.end() - 1);
root->left = buildTree(leftInorder, leftPostorder);
root->right = buildTree(rightInorder, rightPostorder);
return root;
}
int main() {
vector<int> inorder = {9, 3, 15, 20, 7};
vector<int> postorder = {9, 15, 7, 20, 3};
TreeNode* root = buildTree(inorder, postorder);
return 0;
}
```
阅读全文