forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfloor_ceil_in_bst.py
81 lines (63 loc) · 1.94 KB
/
floor_ceil_in_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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
'''
The floor of a key 'k' in a BST is the maximum
value that is smaller than or equal to 'k'.
The ceiling of a key 'k' in a BST is the minimum
value that is greater than or equal to 'k'.
Reference:
https://bit.ly/46uB0a2
Author : Arunkumar
Date : 14th October 2023
'''
from typing import Optional
class TreeNode:
def __init__(self, key: int):
"""
Initialize a TreeNode with the given key.
Args:
key (int): The key value for the node.
"""
self.key = key
self.left: Optional[TreeNode] = None
self.right: Optional[TreeNode] = None
def floor_ceiling(root: Optional[TreeNode], key: int) -> tuple[Optional[int], Optional[int]]:
"""
Find the floor and ceiling values for a given key in a Binary Search Tree (BST).
Args:
root (TreeNode): The root of the BST.
key (int): The key for which to find the floor and ceiling.
Returns:
tuple[Optional[int], Optional[int]]: A tuple containing the floor and ceiling values, respectively.
Examples:
>>> root = TreeNode(10)
>>> root.left = TreeNode(5)
>>> root.right = TreeNode(20)
>>> root.left.left = TreeNode(3)
>>> root.left.right = TreeNode(7)
>>> root.right.left = TreeNode(15)
>>> root.right.right = TreeNode(25)
>>> floor, ceiling = floor_ceiling(root, 8)
>>> floor
7
>>> ceiling
10
>>> floor, ceiling = floor_ceiling(root, 14)
>>> floor
10
>>> ceiling
15
"""
floor_val = None
ceiling_val = None
while root is not None:
if root.key == key:
return root.key, root.key
if key < root.key:
ceiling_val = root.key
root = root.left
else:
floor_val = root.key
root = root.right
return floor_val, ceiling_val
if __name__ == "__main__":
import doctest
doctest.testmod()