m2skills

nodes at k java

Jun 4th, 2018
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. // http://code2begin.blogspot.com
  2. // program to print nodes at a distance K from a given node in binary tree
  3.  
  4. /**
  5.  * Created by MOHIT on 25-05-2018.
  6.  */
  7.  
  8. import java.io.*;
  9. import java.lang.reflect.Array;
  10. import java.util.*;
  11.  
  12. import static java.lang.Integer.max;
  13.  
  14.  
  15. // node class
  16. class node{
  17.     int data;
  18.     node left;
  19.     node right;
  20.  
  21.     // function that returns a pointer to new node
  22.     public node(int element){
  23.         this.data = element;
  24.         this.left = null;
  25.         this.right = null;
  26.        
  27.     }
  28. };
  29.  
  30.  
  31. public class BinaryTree {
  32.     // function to print child nodes at a distance k from the given node
  33.     static void print_nodes_at_K(node root, int K){
  34.         if(root == null || K < 0){
  35.             return;
  36.         }
  37.         if(K == 0){
  38.             System.out.print(root.data + " ");
  39.         }
  40.         if(K > -1) {
  41.             print_nodes_at_K(root.left, K - 1);
  42.             print_nodes_at_K(root.right, K - 1);
  43.         }
  44.     }
  45.  
  46.     public static void main(String arg[]) {
  47.         node head = new node(1);
  48.         head.left = new node(2);
  49.         head.right = new node(3);
  50.         head.left.left = new node(4);
  51.         head.left.right = new node(5);
  52.         head.right.right = new node(6);
  53.         head.left.left.right = new node(7);
  54.         head.right.right.left = new node(8);
  55.         head.left.left.right.left = new node(9);
  56.         head.left.left.right.left.left = new node(10);
  57.         head.right.right.left.right = new node(11);
  58.        
  59.         System.out.print("Nodes at distance 2 from the root node are : ");
  60.         print_nodes_at_K(head, 2);      
  61.     }
  62. }
Add Comment
Please, Sign In to add comment