m2skills

ancestor java

Jun 3rd, 2018
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.17 KB | None | 0 0
  1. // http://code2begin.blogspot.com
  2. // program to print all ancestors of a node in a given 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.    
  33.     // function to print all the ancestors of a node
  34.     static boolean ancestors(node root, int target){
  35.         // if the current node is null then return false
  36.         if(root == null){
  37.             return false;
  38.         }
  39.         // if the current node is our target node then we return true
  40.         if(root.data == target){
  41.             return true;
  42.         }
  43.         // here we recursively check if the current node if the ancestor of the target node then we need to print it
  44.         // the target node might lie in the left or the right subtree
  45.         // thus we take or of the the returned boolean values
  46.         if(ancestors(root.left, target) || ancestors(root.right, target)){
  47.             System.out.print(root.data + " ");
  48.             return true;
  49.         }
  50.    
  51.         return false;
  52.     }
  53.    
  54.  
  55.     public static void main(String arg[]) {
  56.         node head = new node(1);
  57.         head.left = new node(2);
  58.         head.right = new node(3);
  59.         head.left.left = new node(4);
  60.         head.left.right = new node(5);
  61.         head.right.right = new node(6);
  62.         head.left.left.right = new node(7);
  63.         head.right.right.left = new node(8);
  64.         head.left.left.right.left = new node(9);
  65.         head.left.left.right.left.left = new node(10);
  66.         head.right.right.left.right = new node(11);
  67.  
  68.         System.out.println("All ancestors of node 10 are : ");
  69.         ancestors(head, 10);
  70.         System.out.println("\nAll ancestors of node 5 are : ");
  71.         ancestors(head, 5);
  72.         System.out.println("\nAll ancestors of node 8 are : ");
  73.         ancestors(head, 8);
  74.  
  75.     }
  76. }
Add Comment
Please, Sign In to add comment