【题目描述】Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
【解题思路】与上题相似
【考查内容】树,递归
/**
* 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()!=inorder.size())
return NULL;
return build(preorder,0,preorder.size()-1,inorder,0,inorder.size()-1);
}
TreeNode* build(vector<int> &preorder,int l1,int r1,vector<int> &inorder,int l2,int r2){
if(l1>r1||l2>r2)
return NULL;
int r = preorder[l1],i,cnt=0;
for(i=l2;inorder[i]!=r;i++,cnt++);
TreeNode * root = new TreeNode(preorder[l1]);
root->left = build(preorder,l1+1,l1+cnt,inorder,l2,i-1);
root->right = build(preorder,l1+cnt+1,r1,inorder,i+1,r2);
return root;
}
};
`