[InterviewBit] Binary Tree From Inorder And Postorder

Binary Tree From Inorder And Postorder

  • 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(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);
}

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