This function prints the nodes in a BST that are in the range k1 to k2 inclusive
(root: Optional[Node], k1: int, k2: int)
| 3 | |
| 4 | |
| 5 | def print_in_range(root: Optional[Node], k1: int, k2: int) -> None: |
| 6 | """This function prints the nodes in a BST that are in the range k1 to k2 inclusive""" |
| 7 | |
| 8 | # If the tree is empty, return |
| 9 | if root is None: |
| 10 | return |
| 11 | |
| 12 | # If the root value is in the range, print the root value |
| 13 | if k1 <= root.data <= k2: |
| 14 | print_in_range(root.left, k1, k2) |
| 15 | print(root.data) |
| 16 | print_in_range(root.right, k1, k2) |
| 17 | |
| 18 | # If the root value is less than k1, the nodes in the range will be in the right subtree |
| 19 | elif root.data < k1: |
| 20 | print_in_range( |
| 21 | root.right, k1, k2 |
| 22 | ) # Fixed: original had left, which is incorrect |
| 23 | |
| 24 | # If the root value is greater than k2, the nodes in the range will be in the left subtree |
| 25 | else: |
| 26 | print_in_range( |
| 27 | root.left, k1, k2 |
| 28 | ) # Fixed: original had right, which is incorrect |