/**
* 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> &preorder, vector<int> &inorder)
{
if(preorder.size()==0||inorder.size()==0)
return NULL;
if(preorder.size()!=inorder.size())
return NULL;
int length=preorder.size();
return ReConstruct(preorder,0,length-1,inorder,0,length-1);
}
TreeNode* ReConstruct(vector<int> &preorder,int PreBegin,int PreEnd,vector<int> &inorder,int InBegin,int InEnd)
{
TreeNode* root=new TreeNode(preorder[PreBegin]);
int rootInorder=InBegin;
while(rootInorder<=InEnd)
{
if(inorder[rootInorder]==preorder[PreBegin])
break;
++rootInorder;
}
if(rootInorder==InEnd && inorder[rootInorder]==preorder[PreBegin])
rootInorder=InEnd;
int leftLength=rootInorder-InBegin;
if(leftLength>0)
root->left=ReConstruct(preorder,PreBegin+1,leftLength+PreBegin,inorder,InBegin,rootInorder-1);
if(leftLength<InEnd-InBegin)
root->right=ReConstruct(preorder,leftLength+PreBegin+1,PreEnd,inorder,rootInorder+1,InEnd);
return root;
}
};
Construct Binary Tree from Preorder and Inorder Traversal
最新推荐文章于 2019-12-27 13:16:14 发布