-
Notifications
You must be signed in to change notification settings - Fork 0
/
106. Construct Binary Tree from Inorder and Postorder Traversal
70 lines (57 loc) · 1.89 KB
/
106. Construct Binary Tree from Inorder and Postorder Traversal
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/**
* 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 {
private int ind;
private Map<Integer, Integer> mp;
private TreeNode helper(int[] inorder, int[] postorder, int l, int r) {
if(l > r) return null;
int val = postorder[ind];
TreeNode root = new TreeNode(val);
int p = mp.get(val);
ind--;
root.right = helper(inorder, postorder, p + 1, r);
root.left = helper(inorder, postorder, l, p - 1);
return root;
}
public TreeNode buildTree(int[] inorder, int[] postorder) {
ind = postorder.length - 1;
mp = new HashMap<>();
for(int i = 0; i < inorder.length; i++)
mp.put(inorder[i], i);
return helper(inorder, postorder, 0, inorder.length - 1);
}
}
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
n = len(inorder)
mp = {inorder[i] : i for i in range(n)}
self.i = n - 1
def helper(l, r):
if self.i < 0 or l > r:
return None
part = mp[postorder[self.i]]
self.i -= 1
root = TreeNode(inorder[part])
root.right = helper(part + 1, r)
root.left = helper(l, part - 1)
return root
return helper(0, n - 1)