题目描述
根据一棵树的前序遍历与中序遍历构造二叉树。
注意:
你可以假设树中没有重复的元素。
例如,给出
样例
前序遍历 preorder = [3,9,20,15,7]
中序遍历 inorder = [9,3,15,20,7]
返回如下的二叉树:
3
/ \
9 20
/ \
15 7
算法1
(暴力枚举) $O(n)$
参考文献
C++ 代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
unordered_map<int, int> hash;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n = preorder.size();
for(int i = 0; i < n; ++i) hash[inorder[i]] = i;
TreeNode* root = dfs(preorder, 0, n - 1, inorder, 0, n - 1);
return root;
}
TreeNode* dfs(vector<int>& preorder,int p_l, int p_r, vector<int>& inorder, int i_l, int i_r){
if(p_l > p_r) return nullptr;
//找到根节点
int val = preorder[p_l];
TreeNode* root = new TreeNode(val);
int k = hash[val];
int len = k - i_l;
root->left = dfs(preorder, p_l + 1, p_l + len, inorder, k - len, k - 1);
root->right = dfs(preorder, p_l + len + 1, p_r, inorder, k + 1, i_r);
return root;
}
};