题解:就是用中序和后序重建二叉树保证每个点不重复值上
这里顺便列下中序和先序的代码,思路都一样用map存储可以节省查找时间,注意边界处理
class Solution {
private:
unordered_map<int, int> inm; // inorder map [inorder[i], i]
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
int n = inorder.size(), i = 0;
for(auto val: inorder) inm[val] = i++; // build inm for dfs
return dfs(inorder, 0, n - 1, postorder, 0, n - 1);
}
TreeNode* dfs(vector<int>& inorder, int ileft, int iright, vector<int>& postorder, int pleft, int pright) {
if(ileft > iright) return nullptr;
int val = postorder[pright]; // root value
TreeNode *root = new TreeNode(val);
if(ileft == iright) return root;
int iroot = inm[val];
int nleft = iroot - ileft; // length of left subtree
root->right = dfs(inorder, iroot + 1, iright, postorder, pleft + nleft, pright - 1);
root->left = dfs(inorder, ileft, iroot - 1, postorder, pleft, pleft + nleft - 1);
return root;
}
};
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
unordered_map<int,int> mp;
public:
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
int i=0,n=inorder.size();
for(auto x:inorder) mp[x]=i++;
return dfs(preorder,0,n-1,inorder,0,n-1);
}
TreeNode *dfs(vector<int> pre,int pL,int pR,vector<int> in,int inL,int inR)
{
if(inL>inR) return nullptr;
int val=pre[pL];
TreeNode *root=new TreeNode(val);
if(inL==inR) return root;
int dis=mp[val]-inL;
root->left=dfs(pre,pL+1,pL+dis,in,inL,inL+dis-1);
root->right=dfs(pre,pL+dis+1,pR,in,inL+dis+1,inR);
return root;
}
};