m2skills

print leafs bt java

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