Skip to content

Commit 878554a

Browse files
Added Day-27 Solution
1 parent 5c25f88 commit 878554a

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
'''
2+
Given inorder and postorder traversal of a tree, construct the binary tree.
3+
4+
Note:
5+
You may assume that duplicates do not exist in the tree.
6+
7+
For example, given
8+
9+
inorder = [9,3,15,20,7]
10+
postorder = [9,15,7,20,3]
11+
Return the following binary tree:
12+
13+
3
14+
/ \
15+
9 20
16+
/ \
17+
15 7
18+
19+
20+
21+
'''
22+
23+
# Definition for a binary tree node.
24+
# class TreeNode:
25+
# def __init__(self, val=0, left=None, right=None):
26+
# self.val = val
27+
# self.left = left
28+
# self.right = right
29+
class Solution:
30+
def formTree(self, postorder, inorder, start, end):
31+
if start > end:
32+
return None
33+
34+
root = TreeNode(postorder[self.postIndex])
35+
self.postIndex -= 1 #decrement
36+
37+
if root is None:
38+
return None
39+
40+
if start == end:
41+
return root
42+
43+
index = self.inorder_hashmap[root.val]
44+
45+
#traversal
46+
root.right = self.formTree(postorder, inorder, index+1, end)
47+
root.left = self.formTree(postorder, inorder, start, index - 1)
48+
return root
49+
50+
def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:
51+
#preorder -> Root, Left, Right
52+
#inorder -> Left, root, Right
53+
#postorder -> Left, Right, Root
54+
55+
self.inorder_hashmap = {}
56+
self.postIndex = len(postorder) - 1
57+
58+
for num, i in enumerate(inorder):
59+
self.inorder_hashmap[i] = num
60+
61+
return self.formTree(postorder, inorder, 0, len(inorder)-1)

0 commit comments

Comments
 (0)