Print BST keys in given Range | O ( 1 ) Space | JavaScript 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 ; Constructed binary tree is 4 / \ 2 7 / \ / \ 1 3 6 10
class node { constructor ( ) { this . data = 0 ; this . left = null ; this . right = null ; } } function RangeTraversal ( root , n1 , n2 ) { if ( root == null ) return ; var curr = root ; while ( curr != null ) { if ( curr . left == null ) { if ( curr . data <= n2 && curr . data >= n1 ) { document . write ( curr . data + " " ) ; } curr = curr . right ; } else { var 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 ) { document . write ( curr . data + " " ) ; } curr = curr . right ; } } } } function newNode ( data ) { temp = new node ( ) ; temp . data = data ; temp . right = null ; temp . left = null ; return temp ; } 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 ) ;