-
Notifications
You must be signed in to change notification settings - Fork 236
/
Copy pathreconstruct-bst.py
58 lines (46 loc) · 1.84 KB
/
reconstruct-bst.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# RECONSTRUCT BST
# This is an input class. Do not edit.
class BST:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
# O(N^2) time and O(N) space
def reconstructBst(preOrderTraversalValues):
# Write your code here.
return reconstructTree(preOrderTraversalValues, 0, len(preOrderTraversalValues) - 1)
def reconstructTree(preOrderValues, start, end):
if start > end:
return None
rootValue = preOrderValues[start]
index = start + 1
while index <= end and preOrderValues[index] < rootValue:
index += 1
leftSubtree = reconstructTree(preOrderValues, start + 1, index - 1)
rightSubtree = reconstructTree(preOrderValues, index, end)
root = BST(rootValue, leftSubtree, rightSubtree)
return root
# This is an input class. Do not edit.
class BST:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
class TreeInfo:
def __init__(self, rootIdx):
self.rootIdx = rootIdx
# O(N) time and space
def reconstructBst(preOrderTraversalValues):
# Write your code here.
treeInfo = TreeInfo(0)
return reconstructBstFromRange(float("-inf"), float("inf"), preOrderTraversalValues, treeInfo)
def reconstructBstFromRange(lowerBound, upperBound, preOrderTraversalValues, currentSubtreeInfo):
if currentSubtreeInfo.rootIdx == len(preOrderTraversalValues):
return None
rootValue = preOrderTraversalValues[currentSubtreeInfo.rootIdx]
if rootValue < lowerBound or rootValue >= upperBound:
return None
currentSubtreeInfo.rootIdx += 1
leftSubtree = reconstructBstFromRange(lowerBound, rootValue, preOrderTraversalValues, currentSubtreeInfo)
rightSubtree = reconstructBstFromRange(rootValue, upperBound, preOrderTraversalValues, currentSubtreeInfo)
return BST(rootValue, leftSubtree, rightSubtree)