class Solution {
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
if(inorder.size()==0)
return NULL;
return traverse(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
}
TreeNode *traverse(vector<int>&inorder,int ibegin,int iend,vector<int>&postorder,int pbegin,int pend)
{
if(ibegin>iend)
return NULL;
TreeNode *root=new TreeNode(postorder[pend]);
int index;
for(int i=ibegin;i<=iend;i++)
{
if(inorder[i]==root->val)
{
index=i;
break;
}
}
TreeNode *left=traverse(inorder,ibegin,index-1,postorder,pbegin,pbegin+index-ibegin-1);
TreeNode *right=traverse(inorder,index+1,iend,postorder,pbegin+index-ibegin,pend-1);
root->left=left;
root->right=right;
return root;
}
};
Construct Binary Tree from Inorder and Postorder Traversal
最新推荐文章于 2021-02-03 15:56:42 发布