-
Notifications
You must be signed in to change notification settings - Fork 0
/
find_Closest_Node.py
50 lines (45 loc) · 1.17 KB
/
find_Closest_Node.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
"""class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def findClosestNode(root, K):
closest = root
while root:
if root.val == K:
return root
if abs(root.val - K) < abs(closest.val - K):
closest = root
if K < root.val:
root = root.left
else:
root = root.right
return closest
"""
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def findClosestNode(root, K):
closest = root
while root:
if root.val == K:
return root
if abs(root.val - K) < abs(closest.val - K):
closest = root
if K < root.val:
root = root.left
else:
root = root.right
return closest
# Define the BST
root = TreeNode(15)
root.left = TreeNode(10)
root.right = TreeNode(20)
root.left.left = TreeNode(5)
root.left.right = TreeNode(12)
root.right.right = TreeNode(25)
# Call the function
result = findClosestNode(root, 7)
print(result.val) # Output: 5