Construct Binary Tree from Inorder and Postorder Traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
1 class Solution { 2 public: 3 TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) { 4 return build_Tree(inorder.begin(), inorder.end(), postorder.begin(), postorder.end()); 5 } 6 7 TreeNode *build_Tree(vector<int>::iterator in_b, vector<int>::iterator in_e, vector<int>::iterator post_b, vector<int>::iterator post_e){ 8 if(in_b == in_e || post_b == post_e) return NULL; 9 10 TreeNode *root = new TreeNode(*prev(post_e)); 11 auto root_p = find(in_b, in_e, *prev(post_e)); 12 auto tmp = next(post_b, distance(in_b, root_p)); 13 14 root->left = build_Tree(in_b, root_p, post_b, tmp); 15 root->right = build_Tree(next(root_p), in_e, tmp, prev(post_e)); 16 17 return root; 18 } 19 };