-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConstruct binary tree from preorder and postorder
47 lines (35 loc) · 1.72 KB
/
Construct binary tree from preorder 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Construct binary tree from preorder and postorder traversal - medium - 02/09/2023
class Solution {
private HashMap<Integer, Integer> postorderMap= new HashMap<>();
public TreeNode constructFromPrePost(int[] preorder, int[] postorder)
{
for(int i= 0; i< postorder.length; i++)
postorderMap.put(postorder[i], i);
return constructBT(preorder, 0, preorder.length - 1, 0, postorder.length - 1);
}
public TreeNode constructBT(int[] preorder, int preorderStart, int preorderEnd, int postorderStart, int postorderEnd)
{
if(preorderStart > preorderEnd)
return null;
int rootData= preorder[preorderStart];
if(preorderStart == preorderEnd)
return new TreeNode(rootData, null, null);
int LeftrootIndex= postorderMap.get(preorder[preorderStart + 1]);
int leftSubtreeSize= LeftrootIndex - postorderStart + 1;
TreeNode left= constructBT(preorder, preorderStart+ 1, preorderStart + leftSubtreeSize, postorderStart, LeftrootIndex);
TreeNode right= constructBT(preorder, preorderStart + leftSubtreeSize + 1, preorderEnd, LeftrootIndex + 1, preorderEnd - 1);
TreeNode node= new TreeNode(rootData, left, right);
return node;
}
}
// Optimized
int preIndex = 0, posIndex = 0;
public TreeNode constructFromPrePost(int[]pre, int[]post) {
TreeNode root = new TreeNode(pre[preIndex++]);
if (root.val != post[posIndex])
root.left = constructFromPrePost(pre, post);
if (root.val != post[posIndex])
root.right = constructFromPrePost(pre, post);
posIndex++;
return root;
}