Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given
preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]
Return the following binary tree:
3
/ \
9 20
/ \
15 7
第一次写树的题,心理上还是蛮挑战的,记录之。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* tree(vector<int>& preorder, vector<int>& inorder,int pa,int pb,int ia,int ib){
if(pb<pa)
return NULL;
TreeNode *t=new TreeNode(preorder[pa]);
if(pb==pa)
return t;
int k;
for(k=ia;k<=ib;++k)
if(inorder[k]==preorder[pa])
break;
t->left=tree(preorder,inorder,pa+1,pa+k-ia,ia,k-1);
t->right=tree(preorder,inorder,pa+k-ia+1,pb,k+1,ib);
return t;
}
TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
int n=preorder.size();
if(n==0)
return NULL;
TreeNode *t=tree(preorder,inorder,0,n-1,0,n-1);
return t;
}
};