Print BST keys in given Range | O ( 1 ) Space | Python3 code to print BST keys in given Range in constant space using Morris traversal . Helper function to create a new node ; Function to print the keys in range ; check if current node lies between n1 and n2 ; finding the inorder predecessor - inorder predecessor is the right most in left subtree or the left child , i . e in BST it is the maximum ( right most ) in left subtree . ; check if current node lies between n1 and n2 ; Driver Code ; Constructed binary tree is 4 / \ 2 7 / \ / \ 1 3 6 10
class newNode : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def RangeTraversal ( root , n1 , n2 ) : NEW_LINE INDENT if root == None : NEW_LINE INDENT return NEW_LINE DEDENT curr = root NEW_LINE while curr : NEW_LINE INDENT if curr . left == None : NEW_LINE INDENT if curr . data <= n2 and curr . data >= n1 : NEW_LINE INDENT print ( curr . data , end = " ▁ " ) NEW_LINE DEDENT curr = curr . right NEW_LINE DEDENT else : NEW_LINE INDENT pre = curr . left NEW_LINE while ( pre . right != None and pre . right != curr ) : NEW_LINE INDENT pre = pre . right NEW_LINE DEDENT if pre . right == None : NEW_LINE INDENT pre . right = curr ; NEW_LINE curr = curr . left NEW_LINE DEDENT else : NEW_LINE INDENT pre . right = None NEW_LINE if curr . data <= n2 and curr . data >= n1 : NEW_LINE INDENT print ( curr . data , end = " ▁ " ) NEW_LINE DEDENT curr = curr . right NEW_LINE DEDENT DEDENT DEDENT DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = newNode ( 4 ) NEW_LINE root . left = newNode ( 2 ) NEW_LINE root . right = newNode ( 7 ) NEW_LINE root . left . left = newNode ( 1 ) NEW_LINE root . left . right = newNode ( 3 ) NEW_LINE root . right . left = newNode ( 6 ) NEW_LINE root . right . right = newNode ( 10 ) NEW_LINE RangeTraversal ( root , 4 , 12 ) NEW_LINE DEDENT