Traversing the binary tree is configured in accordance with the sequence preorder traversal of a tree.
Note:
You can assume that the tree does not duplicate elements.
For example, given
Preorder traversal preorder = [3,9,20,15,7]
preorder inorder = [9,3,15,20,7]
returns the following binary tree:
3
/ 9 20
/ 15 7
Source: stay button (LeetCode)
link: https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal
ideas: preorder traversal is about roots, preorder is left the right, then each root node is found in the pre-order traversing the inside, and then a step to find each narrow root (recursive
class Solution {
public:
unordered_map<int,int> pos;//目的是快速找到一个值在inorder内的下标
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n=preorder.size();
for(int i=0;i<n;++i){
pos[inorder[i]]=i;
}
return dfs(preorder,inorder,0,n-1,0,n-1);
}
TreeNode* dfs(vector<int>& pre,vector<int>& in,int pl,int pr,int il,int ir){
if(pl>pr)return NULL;//进行到找不到结点的时候就返回
int len=pos[pre[pl]]-il;
auto root = new TreeNode(pre[pl]);
root->left=dfs(pre,in,pl+1,pl+len,il,il+len-1);
root->right=dfs(pre,in,pl+len+1,pr,il+len+1,ir);
return root;
}
};