|
| 1 | +""" |
| 2 | +In a binary search tree (BST): |
| 3 | +* The floor of key 'k' is the maximum value that is smaller than or equal to 'k'. |
| 4 | +* The ceiling of key 'k' is the minimum value that is greater than or equal to 'k'. |
| 5 | +
|
| 6 | +Reference: |
| 7 | +https://bit.ly/46uB0a2 |
| 8 | +
|
| 9 | +Author : Arunkumar |
| 10 | +Date : 14th October 2023 |
| 11 | +""" |
| 12 | +from __future__ import annotations |
| 13 | + |
| 14 | +from collections.abc import Iterator |
| 15 | +from dataclasses import dataclass |
| 16 | + |
| 17 | + |
| 18 | +@dataclass |
| 19 | +class Node: |
| 20 | + key: int |
| 21 | + left: Node | None = None |
| 22 | + right: Node | None = None |
| 23 | + |
| 24 | + def __iter__(self) -> Iterator[int]: |
| 25 | + if self.left: |
| 26 | + yield from self.left |
| 27 | + yield self.key |
| 28 | + if self.right: |
| 29 | + yield from self.right |
| 30 | + |
| 31 | + def __len__(self) -> int: |
| 32 | + return sum(1 for _ in self) |
| 33 | + |
| 34 | + |
| 35 | +def floor_ceiling(root: Node | None, key: int) -> tuple[int | None, int | None]: |
| 36 | + """ |
| 37 | + Find the floor and ceiling values for a given key in a Binary Search Tree (BST). |
| 38 | +
|
| 39 | + Args: |
| 40 | + root: The root of the binary search tree. |
| 41 | + key: The key for which to find the floor and ceiling. |
| 42 | +
|
| 43 | + Returns: |
| 44 | + A tuple containing the floor and ceiling values, respectively. |
| 45 | +
|
| 46 | + Examples: |
| 47 | + >>> root = Node(10) |
| 48 | + >>> root.left = Node(5) |
| 49 | + >>> root.right = Node(20) |
| 50 | + >>> root.left.left = Node(3) |
| 51 | + >>> root.left.right = Node(7) |
| 52 | + >>> root.right.left = Node(15) |
| 53 | + >>> root.right.right = Node(25) |
| 54 | + >>> tuple(root) |
| 55 | + (3, 5, 7, 10, 15, 20, 25) |
| 56 | + >>> floor_ceiling(root, 8) |
| 57 | + (7, 10) |
| 58 | + >>> floor_ceiling(root, 14) |
| 59 | + (10, 15) |
| 60 | + >>> floor_ceiling(root, -1) |
| 61 | + (None, 3) |
| 62 | + >>> floor_ceiling(root, 30) |
| 63 | + (25, None) |
| 64 | + """ |
| 65 | + floor_val = None |
| 66 | + ceiling_val = None |
| 67 | + |
| 68 | + while root: |
| 69 | + if root.key == key: |
| 70 | + floor_val = root.key |
| 71 | + ceiling_val = root.key |
| 72 | + break |
| 73 | + |
| 74 | + if key < root.key: |
| 75 | + ceiling_val = root.key |
| 76 | + root = root.left |
| 77 | + else: |
| 78 | + floor_val = root.key |
| 79 | + root = root.right |
| 80 | + |
| 81 | + return floor_val, ceiling_val |
| 82 | + |
| 83 | + |
| 84 | +if __name__ == "__main__": |
| 85 | + import doctest |
| 86 | + |
| 87 | + doctest.testmod() |
0 commit comments