原题:
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.empty()||inorder.empty()) return NULL;
return make(preorder.begin(),preorder.end(), inorder.begin(), inorder.end());
}
TreeNode *make(vector<int>::iterator preleft, vector<int>::iterator preright, vector<int>::iterator inleft,vector<int>::iterator inright){
if (preright==preleft) return NULL;
if (inright==inleft) return NULL;
TreeNode *root = new TreeNode(*preleft);
vector<int>::iterator iRoot = find(inleft , inright , root->val);
int leftsize = iRoot-inleft;
root->right = make(preleft+leftsize+1, preright, iRoot+1, inright);
root->left = make(preleft+1, preleft+leftsize+1, inleft, iRoot);
return root;
}
};
AC