forked from anmol/algorithm_python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstruct_tree.py
More file actions
34 lines (26 loc) · 844 Bytes
/
Copy pathconstruct_tree.py
File metadata and controls
34 lines (26 loc) · 844 Bytes
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
#!/usr/bin/env python2.7
from tree import BinaryTree
def construct_tree(inorder, preorder):
global index
node = preorder[0]
t = BinaryTree(node)
index += 1
left_inorder = inorder.split(node)[0]
right_inorder = inorder.split(node)[1]
if len(left_inorder) > 1 and len(preorder[index:]) > 0:
t.insert_left(construct_tree(left_inorder, preorder[index:]))
else:
t.insert_left(BinaryTree(left_inorder))
index += 1
if len(right_inorder) > 1 and len(preorder[index:]) > 0:
t.insert_right(construct_tree(right_inorder, preorder[index:]))
else:
t.insert_right(BinaryTree(right_inorder))
index += 1
return t
if __name__ == "__main__":
inorder = 'DBEAFC'
preorder = 'ABDECF'
index = 0
t = construct_tree(inorder, preorder)
t.traverse()