Floor and Ceil from a BST | A binary tree node has key , . left child and right child ; Helper function to find floor and ceil of a given key in BST ; Display the floor and ceil of a given key in BST . If key is less than the min key in BST , floor will be - 1 ; If key is more than the max key in BST , ceil will be - 1 ; ; Variables ' floor ' and ' ceil ' are passed by reference ; Driver code
class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . data = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def floorCeilBSTHelper ( root , key ) : NEW_LINE INDENT global floor , ceil NEW_LINE while ( root ) : NEW_LINE INDENT if ( root . data == key ) : NEW_LINE INDENT ceil = root . data NEW_LINE floor = root . data NEW_LINE return NEW_LINE DEDENT if ( key > root . data ) : NEW_LINE INDENT floor = root . data NEW_LINE root = root . right NEW_LINE DEDENT else : NEW_LINE INDENT ceil = root . data NEW_LINE root = root . left NEW_LINE DEDENT DEDENT DEDENT def floorCeilBST ( root , key ) : NEW_LINE INDENT global floor , ceil NEW_LINE floor = - 1 NEW_LINE ceil = - 1 NEW_LINE floorCeilBSTHelper ( root , key ) NEW_LINE print ( key , floor , ceil ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT floor , ceil = - 1 , - 1 NEW_LINE root = Node ( 8 ) NEW_LINE root . left = Node ( 4 ) NEW_LINE root . right = Node ( 12 ) NEW_LINE root . left . left = Node ( 2 ) NEW_LINE root . left . right = Node ( 6 ) NEW_LINE root . right . left = Node ( 10 ) NEW_LINE root . right . right = Node ( 14 ) NEW_LINE for i in range ( 16 ) : NEW_LINE INDENT floorCeilBST ( root , i ) NEW_LINE DEDENT DEDENT