m2skills

deepest leaf java

Jun 1st, 2018
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.11 KB | None | 0 0
  1. // http://code2begin.blogspot.com
  2. // program to find the deepest leaf 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.util.*;
  10. import static java.lang.Integer.max;
  11.  
  12.  
  13. // node class
  14. class node{
  15.     int data;
  16.     node left;
  17.     node right;
  18.  
  19.     // function that returns a pointer to new node
  20.     public node(int element){
  21.         this.data = element;
  22.         this.left = null;
  23.         this.right = null;
  24.        
  25.     }
  26. };
  27.  
  28.  
  29. public class BinaryTree {
  30.  
  31.     static int max_level = -1;
  32.     static int deepest_leaf = -9999;
  33.  
  34.     static int deepest_level_leaf_node(node root){
  35.         max_level = -1;
  36.         deepest_leaf = -9999;
  37.         deepest_level_leaf_node_helper(root, -1);
  38.         return deepest_leaf;
  39.     }
  40.  
  41.     // function to print the deepest leaf node in the binary tree using inorder traversal method
  42.     static void deepest_level_leaf_node_helper(node root, int level){
  43.         // if the tree is empty or if we reach a leaf node then return 0
  44.         if (root == null){
  45.             return;
  46.         }
  47.         // check in the left subtree for the element
  48.         // if found then return the level
  49.         deepest_level_leaf_node_helper(root.left, level + 1);
  50.         if(root.left == null && root.right == null && max_level < level){
  51.             max_level = max(max_level, level);
  52.             deepest_leaf = root.data;
  53.         }
  54.         deepest_level_leaf_node_helper(root.right, level + 1);
  55.     }
  56.  
  57.  
  58.     public static void main(String arg[]) {
  59.         node head = new node(1);
  60.         head.left = new node(2);
  61.         head.right = new node(3);
  62.         head.left.left = new node(4);
  63.         head.left.right = new node(5);
  64.         head.right.right = new node(6);
  65.         head.left.left.right = new node(7);
  66.         head.right.right.left = new node(8);
  67.         head.left.left.right.left = new node(9);
  68.         head.left.left.right.left.left = new node(10);
  69.         head.right.right.left.right = new node(11);
  70.         System.out.println("Deepest Level leaf node in the above binary tree is : " + deepest_level_leaf_node(head));
  71.  
  72.     }
  73. }
Add Comment
Please, Sign In to add comment