Skip to content

Commit 9f43d0b

Browse files
committed
construct binary tree from preorder and inorder
1 parent e853f5e commit 9f43d0b

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
class Node:
2+
def __init__(self, data):
3+
self.data = data
4+
self.left = None
5+
self.right = None
6+
7+
8+
class Solution:
9+
def preorder(self, start):
10+
if start is None:
11+
return
12+
13+
print(start.data)
14+
self.preorder(start.left)
15+
self.preorder(start.right)
16+
17+
18+
def constructBinaryTree(self, preorder: list[int], inorder: list[int]):
19+
if len(inorder) == 0:
20+
return
21+
if len(preorder) == 1:
22+
return Node(preorder[0])
23+
idx = inorder.index(preorder.pop(0)) # pop element from preorder and save the index of it in inorder.
24+
root = Node(inorder[idx]) # created a node of popped element from inorder list
25+
26+
root.left = self.constructBinaryTree(preorder, inorder[:idx])
27+
root.right = self.constructBinaryTree(preorder, inorder[idx + 1:])
28+
29+
return root
30+
31+
32+
preorder = [1, 2, 4, 8, 9, 5, 10, 11, 3, 6, 7]
33+
inorder = [8, 4, 9, 2, 10, 5, 11, 1, 6, 3, 7]
34+
tree = Solution()
35+
root = tree.constructBinaryTree(preorder, inorder)
36+
tree.preorder(root)

0 commit comments

Comments
 (0)