gumgum's Garden🌼

Ceil and Floor in a BST

Ceil

Ceil of a number xx is the immediate greater number than xximage_1_20240330235536.png

def findCeil(self,root, x):
    ans = -1
    def helper(root):
        nonlocal ans
        if root is None:
            return
    		if x > root.val:
    			helper(root.right)
    		elif x < root.val:
    			ans = root.val
    			helper(root.left)
    		else:
    			ans = root.val
	helper(root)
	return ans

Note: Iterative and Recursive approach to this solution is same

Floor

Floor of a number xx is the immediate smaller number than xximage_20240331000808.png

def findFloor(self,root, x):
	ans = -1
	def helper(root):
		nonlocal ans
		if root is None:
			return
		if x > root.val:
			ans = root.val
			helper(root.right)
		elif x < root.val:
			helper(root.left)
		else:
			ans = root.val
	helper(root)
	return ans

Note: Iterative and Recursive approach to this solution is same