Construct Binary Tree From Inorder And Preorder
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(vector<int>& A, unordered_map<int, int>& B, int i, int l, int r) { if(l > r) return NULL; TreeNode* res = new TreeNode(A[i]); if(l != r) { int mid = B[A[i]]; res->left = helper(A,B,i + 1, l, mid - 1); res->right = helper(A,B,i + mid - l + 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 < B.size(); i++) mp[B[i]] = i; return helper(A,mp,0,0,B.size() - 1); }
|