/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder)
{
if(postorder.size()==0||inorder.size()==0)
return NULL;
if(postorder.size()!=inorder.size())
return NULL;
int length=postorder.size();
return ReConstruct(postorder,0,length-1,inorder,0,length-1);
}
TreeNode* ReConstruct(vector<int> &postorder,int PostBegin,int PostEnd,vector<int> &inorder,int InBegin,int InEnd)
{
TreeNode* root=new TreeNode(postorder[PostEnd]);
int rootInorder=InBegin;
while(rootInorder<=InEnd)
{
if(inorder[rootInorder]==postorder[PostEnd])
break;
++rootInorder;
}
if(rootInorder==InEnd && inorder[rootInorder]==postorder[PostEnd])
rootInorder=InEnd;
int leftLength=rootInorder-InBegin;
if(leftLength>0)
root->left=ReConstruct(postorder,PostBegin,leftLength+PostBegin-1,inorder,InBegin,rootInorder-1);
if(leftLength<InEnd-InBegin)
root->right=ReConstruct(postorder,leftLength+PostBegin,PostEnd-1,inorder,rootInorder+1,InEnd);
return root;
}
};
Construct Binary Tree from Inorder and Postorder Traversal
最新推荐文章于 2021-02-03 15:56:42 发布