1
+ """
2
+ inorder: [LEFT]root[RIGHT]
3
+ postorder: [LEFT][RIGHT]root
4
+
5
+ First thing we know is the value of root, which is the last element of `postorder`.
6
+ Find the index of the root in `inorder`. So find out the interval of [LEFT] and [RIGHT] in `inorder`.
7
+
8
+ The length of the [LEFT] and [RIGHT] in `inorder` are the same with the length of the [LEFT] and [RIGHT] in `postorder`.
9
+ """
10
+ class Solution (object ):
11
+ def buildTree (self , inorder , postorder ):
12
+ if not inorder or not postorder : return None
13
+
14
+ root = TreeNode (postorder [- 1 ])
15
+ if len (inorder )== 1 : return root
16
+
17
+ r = inorder .index (root .val )
18
+
19
+ leftInOrder = inorder [:r ]
20
+ leftPostOrder = postorder [:r ]
21
+ rightInOrder = inorder [r + 1 :]
22
+ rightPostOrder = postorder [r :len (postorder )- 1 ]
23
+
24
+ root .left = self .buildTree (leftInOrder , leftPostOrder )
25
+ root .right = self .buildTree (rightInOrder , rightPostOrder )
26
+
27
+ return root
28
+ """
29
+ Time: O(NLogN). For each node, we need to do an iteration to its children. To be precise..
30
+ O(N) for constructing root.
31
+
32
+ O(N/2) for constructing root.left
33
+ O(N/2) for constructing root.right
34
+
35
+ O(N/4) for constructing root.left.left
36
+ O(N/4) for constructing root.left.right
37
+ O(N/4) for constructing root.right.left
38
+ O(N/4) for constructing root.right.right
39
+ ...
40
+
41
+ To improve this, we can use a hash table to get the index of `i` below
42
+
43
+
44
+ Space: O(NLogN).
45
+ For each node, we need to construct inorder/postorder arrays of its children.
46
+ We can improve this by using pointers.
47
+ """
48
+
49
+ """
50
+ Improved version.
51
+ Time: O(N).
52
+ Space: O(N). For `index`.
53
+ """
54
+ class Solution (object ):
55
+ def buildTree (self , inorder , postorder ):
56
+ def helper (i , j , k , l ):
57
+ if j - i <= 0 : return None
58
+ if l - k <= 0 : return None
59
+
60
+ root = TreeNode (postorder [l - 1 ])
61
+ if j - i == 1 : return root
62
+
63
+ r = index [root .val ]
64
+
65
+ root .left = helper (i , r , k , k + r - i )
66
+ root .right = helper (r + 1 , j , k + r - i , l - 1 )
67
+ return root
68
+
69
+ index = {} #the index of inorder
70
+ for i , n in enumerate (inorder ): index [n ] = i
71
+ return helper (0 , len (inorder ), 0 , len (postorder ))
0 commit comments