C++生成前序遍历和中序遍历恢复二叉树
时间: 2024-02-04 17:34:33 浏览: 96
题目描述:
输入一棵二叉树的前序遍历和中序遍历,输出该二叉树的后序遍历。
解题思路:
根据二叉树的前序遍历和中序遍历可以确定一棵二叉树。前序遍历的第一个节点是根节点,根据中序遍历可以得到左子树和右子树的节点个数,从而可以将前序遍历和中序遍历分成左子树和右子树的两部分,递归构建左子树和右子树。
递归终止条件为前序遍历和中序遍历为空,此时返回空节点。
C++代码:
```cpp
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
unordered_map<int, int> map;
for (int i = 0; i < inorder.size(); i++) {
map[inorder[i]] = i;
}
return buildTree(preorder, 0, preorder.size() - 1, inorder, 0, inorder.size() - 1, map);
}
private:
TreeNode* buildTree(vector<int>& preorder, int preStart, int preEnd, vector<int>& inorder, int inStart, int inEnd, unordered_map<int, int>& map) {
if (preStart > preEnd || inStart > inEnd) {
return NULL;
}
int rootVal = preorder[preStart];
int rootIndex = map[rootVal];
int leftNodes = rootIndex - inStart;
TreeNode* root = new TreeNode(rootVal);
root->left = buildTree(preorder, preStart + 1, preStart + leftNodes, inorder, inStart, rootIndex - 1, map);
root->right = buildTree(preorder, preStart + leftNodes + 1, preEnd, inorder, rootIndex + 1, inEnd, map);
return root;
}
};
void postorder(TreeNode* root) {
if (root == NULL) {
return;
}
postorder(root->left);
postorder(root->right);
cout << root->val << " ";
}
int main() {
vector<int> preorder = {1, 2, 4, 5, 3, 6};
vector<int> inorder = {4, 2, 5, 1, 3, 6};
Solution solution;
TreeNode* root = solution.buildTree(preorder, inorder);
postorder(root);
return 0;
}
```
输出结果为:
```
4 5 2 6 3 1
```
阅读全文