Print all nodes at distance k from a given node | A binary tree node ; Recursive function to print all the nodes at distance k in tree ( or subtree ) rooted with given root . ; Base Case ; If we reach a k distant node , print it ; Recur for left and right subtrees ; Prints all nodes at distance k from a given target node . The k distant nodes may be upward or downward . This function Returns distance of root from target node , it returns - 1 if target node is not present in tree rooted with root . ; Base Case 1 : If tree is empty , return - 1 ; If target is same as root . Use the downward function to print all nodes at distance k in subtree rooted with target or root ; Recur for left subtree ; Check if target node was found in left subtree ; If root is at distance k from target , print root Note that dl is Distance of root 's left child from   target ; Else go to right subtree and print all k - dl - 2 distant nodes Note that the right child is 2 edges away from left child ; Add 1 to the distance and return value for parent calls ; MIRROR OF ABOVE CODE FOR RIGHT SUBTREE Note that we reach here only when node was not found in left subtree ; If target was neither present in left nor in right subtree ; Let us construct the tree shown in above diagram
class Node { constructor ( item ) { this . data = item ; this . left = null ; this . right = null ; } } var root = null ; function printkdistanceNodeDown ( node , k ) { if ( node == null k < 0 ) { return ; } if ( k == 0 ) { document . write ( node . data ) ; document . write ( " " ) ; return ; } printkdistanceNodeDown ( node . left , k - 1 ) ; printkdistanceNodeDown ( node . right , k - 1 ) ; } function printkdistanceNode ( node , target , k ) { if ( node == null ) { return - 1 ; } if ( node == target ) { printkdistanceNodeDown ( node , k ) ; return 0 ; } var dl = printkdistanceNode ( node . left , target , k ) ; if ( dl != - 1 ) { if ( dl + 1 == k ) { document . write ( node . data ) ; document . write ( " " ) ; } else { printkdistanceNodeDown ( node . right , k - dl - 2 ) ; } return 1 + dl ; } var dr = printkdistanceNode ( node . right , target , k ) ; if ( dr != - 1 ) { if ( dr + 1 == k ) { document . write ( node . data ) ; document . write ( " " ) ; } else { printkdistanceNodeDown ( node . left , k - dr - 2 ) ; } return 1 + dr ; } return - 1 ; } root = new Node ( 20 ) ; root . left = new Node ( 8 ) ; root . right = new Node ( 22 ) ; root . left . left = new Node ( 4 ) ; root . left . right = new Node ( 12 ) ; root . left . right . left = new Node ( 10 ) ; root . left . right . right = new Node ( 14 ) ; var target = root . left . right ; printkdistanceNode ( root , target , 2 ) ;