[LeetCode] 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 /** 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> &inorder, vector<int> &postorder) { 13 if (inorder.empty() || postorder.empty()) 14 return NULL; 15 return buildTree(inorder.begin(), inorder.end() - 1, postorder.begin(), postorder.end() - 1); 16 } 17 template<typename Iter> 18 TreeNode* buildTree(Iter inBegin, Iter inEnd, Iter postBegin, Iter postEnd) { 19 if (inBegin > inEnd) return nullptr; 20 if (postBegin > postEnd) return nullptr; 21 22 TreeNode *root = new TreeNode(*postEnd); 23 Iter in_root_pos = find(inBegin, inEnd, *postEnd); 24 int left_length = in_root_pos - inBegin; 25 root->left = buildTree(inBegin, in_root_pos - 1, postBegin, postBegin + left_length - 1); 26 root->right = buildTree(in_root_pos + 1, inEnd, postBegin + left_length, postEnd - 1); 27 28 return root; 29 } 30 };