Problem:
Given an integer k and a binary search tree, find the floor (less than or equal to) of k, and the ceiling (larger than or equal to) of k. If either does not exist, then print them as None.
Here is the definition of a node for the tree.
-Summary-
1. if root node is empty we return none value for both floor and ceil.
2. if root node is equal with k, return floor and cell with k value
3. if root node is bigger than k, we go left subtree and keep looking for the node match with a "k". (Update ceil while traverse)
4. if root node is smaller than k, we go right subtree and keep looking for the node match with a "k". (Update floor while traverse)
class Node:
def __init__(self, value):
self.left = None
self.right = None
self.value = value
def findCeilingFloor(root_node, k, floor=None, ceil=None):
# Fill this in.
if root_node is None:
return (floor, ceil)
if root_node.value == k:
return (k, k)
if root_node.value > k:
ceil = root_node.value
return findCeilingFloor(root_node.left, k, floor, ceil)
else:
floor = root_node.value
return findCeilingFloor(root_node.right, k, floor, ceil)
root = Node(8)
root.left = Node(4)
root.right = Node(12)
root.left.left = Node(2)
root.left.right = Node(6)
root.right.left = Node(10)
root.right.right = Node(14)
print findCeilingFloor(root, 5)
# (4, 6)
'LeetCode > Problems' 카테고리의 다른 글
LeetCode 226. Invert Binary Tree (0) | 2020.06.20 |
---|---|
Daily Coding Problem #5 (0) | 2020.06.19 |
LeetCode 41. First Missing Positive (0) | 2020.06.18 |
LeetCode 665. Non-decreasing Array (0) | 2020.06.18 |
LeetCode 136. Single Number (0) | 2020.06.17 |
댓글