Print BST keys in given Range | O ( 1 ) Space | Java code to print BST keys in given Range in constant space using Morris traversal . ; 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 ; Helper function to create a new node ; Driver Code ; Constructed binary tree is 4 / \ 2 7 / \ / \ 1 3 6 10
class GfG { static class node { int data ; node left , right ; } static void RangeTraversal ( node root , int n1 , int n2 ) { if ( root == null ) return ; node curr = root ; while ( curr != null ) { if ( curr . left == null ) { if ( curr . data <= n2 && curr . data >= n1 ) { System . out . print ( curr . data + " ▁ " ) ; } curr = curr . right ; } else { node pre = curr . left ; while ( pre . right != null && pre . right != curr ) pre = pre . right ; if ( pre . right == null ) { pre . right = curr ; curr = curr . left ; } else { pre . right = null ; if ( curr . data <= n2 && curr . data >= n1 ) { System . out . print ( curr . data + " ▁ " ) ; } curr = curr . right ; } } } } static node newNode ( int data ) { node temp = new node ( ) ; temp . data = data ; temp . right = null ; temp . left = null ; return temp ; } public static void main ( String [ ] args ) { node root = newNode ( 4 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 7 ) ; root . left . left = newNode ( 1 ) ; root . left . right = newNode ( 3 ) ; root . right . left = newNode ( 6 ) ; root . right . right = newNode ( 10 ) ; RangeTraversal ( root , 4 , 12 ) ; } }