[InterviewBit] Construct Binary Tree From Inorder And Preorder

Construct Binary Tree From Inorder And Preorder

  • Time :
  • Space :
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
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);
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/04/PS/interviewbit/construct-binary-tree-from-inorder-and-preorder/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.