Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
前序和中序重构二叉树;
这里用dfs的思想:
class Solution {
public:
TreeNode *dfs(vector<int> &preorder,int preStart,int preEnd,vector<int> &inorder,int inStart,int inEnd)
{
if(preStart > preEnd)
return NULL;
TreeNode *root = new TreeNode(preorder[preStart]);
int middle;
for(middle=inStart;middle<=inEnd;middle++)
if(inorder[middle] == root->val)
break;
int leftLen = middle-inStart;
root->left = dfs(preorder,preStart+1,preStart+leftLen,inorder,inStart,middle-1);
root->right = dfs(preorder,preStart+leftLen+1,preEnd,inorder,middle+1,inEnd);
return root;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder)
{
int pre = preorder.size(),in = inorder.size();
if(pre==0 || in==0 || pre != in)
return NULL;
return dfs(preorder,0,pre-1,inorder,0,in-1);
}
};
Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
前序和中序重构二叉树;
这里用dfs的思想:
class Solution {
public:
TreeNode *dfs(vector<int> &preorder,int preStart,int preEnd,vector<int> &inorder,int inStart,int inEnd)
{
if(preStart > preEnd)
return NULL;
TreeNode *root = new TreeNode(preorder[preStart]);
int middle;
for(middle=inStart;middle<=inEnd;middle++)
if(inorder[middle] == root->val)
break;
int leftLen = middle-inStart;
root->left = dfs(preorder,preStart+1,preStart+leftLen,inorder,inStart,middle-1);
root->right = dfs(preorder,preStart+leftLen+1,preEnd,inorder,middle+1,inEnd);
return root;
}
TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder)
{
int pre = preorder.size(),in = inorder.size();
if(pre==0 || in==0 || pre != in)
return NULL;
return dfs(preorder,0,pre-1,inorder,0,in-1);
}
};