forked from BasanthreddyA/100DaysOfCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPreorder postorder
More file actions
41 lines (34 loc) · 1.23 KB
/
Preorder postorder
File metadata and controls
41 lines (34 loc) · 1.23 KB
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public TreeNode buildTree(int[] inorder, int[] postorder) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < inorder.length; i++) {
map.put(inorder[i], i);
}
return helper(map, postorder, 0, inorder.length - 1, 0, postorder.length - 1);
}
private TreeNode helper(Map<Integer, Integer> map, int[] postorder, int inLeft, int inRight, int poLeft, int poRight) {
if (inLeft > inRight) {
return null;
}
TreeNode root = new TreeNode(postorder[poRight]);
int inMid = map.get(root.val);
root.left = helper(map, postorder, inLeft, inMid - 1, poLeft, poLeft + inMid - inLeft - 1);
root.right = helper(map, postorder, inMid + 1, inRight, poRight - inRight + inMid, poRight - 1);
return root;
}
}