Given preorder and inorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
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 template<typename Iter> 13 TreeNode *buildTree(Iter preBegin, Iter preEnd, Iter inBegin, Iter inEnd) { 14 if (preBegin > preEnd) return nullptr; 15 if (inBegin > inEnd) return nullptr; 16 17 int root_val = *preBegin; 18 TreeNode *root = new TreeNode(root_val); 19 Iter in_root_pos = find(inBegin, inEnd, root_val); 20 int left_size = in_root_pos - inBegin; 21 root->left = buildTree(preBegin + 1, preBegin + left_size, inBegin, in_root_pos - 1); 22 root->right = buildTree(preBegin + left_size + 1, preEnd, in_root_pos + 1, inEnd); 23 24 return root; 25 } 26 27 TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { 28 if (preorder.empty() || inorder.empty()) 29 return NULL; 30 31 return buildTree(preorder.begin(), preorder.end() - 1, inorder.begin(), inorder.end() - 1); 32 } 33 };