-
Notifications
You must be signed in to change notification settings - Fork 1
/
FindClosestValueInBST.py
50 lines (42 loc) · 1.4 KB
/
FindClosestValueInBST.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
#Approach 1 : Recursive
def findClosestValueInBst(tree, target):
return helper(tree, target, float("inf"))
def helper(tree, target, closest):
if tree is None:
return closest
if abs(target-closest) > abs(target-tree.value):
closest = tree.value
if target < tree.value:
return helper(tree.left, target, closest)
elif target > tree.value:
return helper(tree.right, target, closest)
else:
return closest
#Average:
#Time Complexity: O(logn)
#Space Complexity: O(logn) [Because of Recursive Call Stack]
#Worst: (When there is no branching and just a linear chain)
#Time Complexity: O(n)
#Space Complexity: O(n)
##################################################
#Approach 2 : Iterative
def findClosestValueInBst(tree, target):
return helper(tree, target, float("inf"))
def helper(tree, target, closest):
currentNode = tree
while currentNode is not None:
if abs(target-closest) > abs(target-currentNode.value):
closest = currentNode.value
if target < currentNode.value:
currentNode = currentNode.left
elif target > currentNode.value:
currentNode = currentNode.right
else:
break
return closest
#Average:
#Time Complexity: O(logn)
#Space Complexity: O(1)
#Worst: (When there is no branching and just a linear chain)
#Time Complexity: O(n)
#Space Complexity: O(1)