Binary Tree From Inorder And Postorder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
TreeNode* helper(unordered_map<int,int>& mp, vector<int>& B, int i, int l, int r) { if(l > r) return NULL; TreeNode* res = new TreeNode(B[i]); if(l != r) { int mid = mp[B[i]]; res->left = helper(mp, B, i - (r - mid) - 1, l, mid - 1); res->right = helper(mp,B, i - 1, mid + 1, r); } return res; } TreeNode* Solution::buildTree(vector<int> &A, vector<int> &B) { unordered_map<int, int> mp; for(int i = 0; i < A.size(); i++) mp[A[i]] = i; return helper(mp, B, B.size() - 1, 0, A.size() - 1); }
|