Print All The Nodes Which are X distance from the Root

Objective: Given Binary Tree, Print all the nodes which are X distance from the root

Example :

Nodes at X distances from root

Nodes at X distances from root

Appraoch:

  • Idea is very simple.
  • Do the preorder traversal, pass x as parameter.
  • While going down, at each level, keep reducing the x by 1
  • When x = 0 , the means you have reached to the nodes which are at x distance from root, Print them.

Complete Code:

Output:
Nodes at 3 distance from root : 
 6 7 9

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

You may also like...

  • Ramachandran Krishnan

    Code should be like that
    public void print(Node root, int k) {
    if (root != null) {
    if (k == 0) {
    System.out.print(” ” + root.data);
    }
    print(root.left, –k);
    print(root.right, –k);
    }
    }

    • eugen_nw

      I’d rather go with:

      public void print(Node root, int k) {

      if (root == null) {
      return;
      }

      if (k == 0) {
      System.out.print(” ” + root.data);
      return; // there’s no point in iterating any further
      }
      k–;
      print(root.left, k);
      print(root.right, k);
      }

%d bloggers like this: