题目
输入一棵二叉树前序遍历和中序遍历的结果,请重建该二叉树。
注意:
二叉树中每个节点的值都互不相同;
输入的前序遍历和中序遍历一定合法;
样例
给定:
前序遍历是:[3, 9, 20, 15, 7]
中序遍历是:[9, 3, 15, 20, 7]
返回:[3, 9, 20, null, null, 15, 7, null, null, null, null]
返回的二叉树如下所示:
3
/ \
9 20
/ \
15 7
模板题,不多说,直接上代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
unordered_map<int, int> pos;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
for (int i = 0; i < inorder.size(); i++) {
pos[inorder[i]] = i;
}
return build(preorder, inorder, 0, inorder.size() - 1, 0, preorder.size() - 1);
}
TreeNode* build(const vector<int> &preorder, const vector<int> &inorder, int il, int ir, int pl, int pr) {
if (il > ir || pl > pr) return nullptr; // 可以防止preorder, inorder为空的情况
TreeNode *root = new TreeNode(preorder[pl]);
int k = pos[preorder[pl]];
root->left = build(preorder, inorder, il, k - 1, pl + 1, pl + k - il);
root->right = build(preorder, inorder, k + 1, ir, pl + k -il + 1, pr);
return root;
}
};