前序+中序:
后序+中序也是一个道理:
class Solution {
public:
unordered_map<int,int> hash;
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
for(int i = 0;i < inorder.size();i++){
hash[inorder[i]] = i;
}
return TreeRecur(0,0,preorder.size()-1,preorder);
}
TreeNode* TreeRecur(int rooti,int lefti,int righti,vector<int>& preorder){
if(lefti > righti)//等于的时候不要退出,说明是叶子结点,需要构建
return nullptr;
TreeNode* root = new TreeNode(preorder[rooti]);
int index = hash[preorder[rooti]];
root->left = TreeRecur(rooti+1,lefti,index-1,preorder);
root->right = TreeRecur(rooti+1+(index-lefti),index+1,righti,preorder);
return root;
}
};