Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
Solution: Recursion.
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { 13 return buildTreeRe(preorder.begin(), inorder.begin(), preorder.size()); 14 } 15 16 TreeNode* buildTreeRe(vector<int>::iterator preorder, vector<int>::iterator inorder, int N) 17 { 18 if(N <= 0) return NULL; 19 vector<int>::iterator it = find(inorder, inorder + N, *preorder); 20 int pos = it - inorder; 21 TreeNode* root = new TreeNode(*preorder); 22 root->left = buildTreeRe(preorder+1, inorder, pos); 23 root->right = buildTreeRe(preorder+pos+1, inorder+pos+1, N-1-pos); 24 return root; 25 } 26 };