Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // program to print nodes at a distance K from a given node in binary tree
- /**
- * Created by MOHIT on 25-05-2018.
- */
- import java.io.*;
- import java.lang.reflect.Array;
- import java.util.*;
- import static java.lang.Integer.max;
- // node class
- class node{
- int data;
- node left;
- node right;
- // function that returns a pointer to new node
- public node(int element){
- this.data = element;
- this.left = null;
- this.right = null;
- }
- };
- public class BinaryTree {
- // function to print child nodes at a distance k from the given node
- static void print_nodes_at_K(node root, int K){
- if(root == null || K < 0){
- return;
- }
- if(K == 0){
- System.out.print(root.data + " ");
- }
- if(K > -1) {
- print_nodes_at_K(root.left, K - 1);
- print_nodes_at_K(root.right, K - 1);
- }
- }
- public static void main(String arg[]) {
- node head = new node(1);
- head.left = new node(2);
- head.right = new node(3);
- head.left.left = new node(4);
- head.left.right = new node(5);
- head.right.right = new node(6);
- head.left.left.right = new node(7);
- head.right.right.left = new node(8);
- head.left.left.right.left = new node(9);
- head.left.left.right.left.left = new node(10);
- head.right.right.left.right = new node(11);
- System.out.print("Nodes at distance 2 from the root node are : ");
- print_nodes_at_K(head, 2);
- }
- }
Add Comment
Please, Sign In to add comment