forked from super30admin/Trees-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ContructTreeOptimal.py
42 lines (20 loc) · 983 Bytes
/
ContructTreeOptimal.py
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
class Solution(object):
def buildTree(self, preorder, inorder):
#HashMap to store element and map to their index
inorderMap = {}
for i in range(len(inorder)):
inorderMap[inorder[i]] = i
# Helper fuction
def helper(preStart, start, end):
if start > end:
return None
#Getting the root value to traverse & create TreeNode
rootVal = preorder[preStart]
root = TreeNode(rootVal)
#Index of rootValue to slice the left & right of subtree
rootIndex = inorderMap[rootVal]
#Recursive call left & right in the Tree
root.left = helper(preStart + 1, start, rootIndex - 1)
root.right = helper(preStart + rootIndex - start + 1,rootIndex +1, end)
return root
return helper(preorder, 0, len(inorder) -1)