m2skills

width bt java

Jun 4th, 2018
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.21 KB | None | 0 0
  1. // http://code2begin.blogspot.com
  2. // program to print width of a given 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. public class BinaryTree {
  25.  
  26.     // function to print the width of the binary tree
  27.     static int width(node root){
  28.         if(root == null){
  29.             return 0 ;
  30.         }
  31.        
  32.         // creating a Queue for storing node for level wise traversal
  33.         ArrayList Q = new ArrayList<node>();
  34.         Q.add(root);
  35.         int result = 0;
  36.        
  37.         while(!Q.isEmpty()){
  38.             // store the current size of the Q
  39.             int count = Q.size();
  40.            
  41.             // find out the max width
  42.             result = max(result, count);
  43.            
  44.             while(count > 0) {
  45.                 // pop the first node from the queue
  46.                 node Node = (node)Q.get(0);
  47.                 Q.remove(0);
  48.                
  49.                 // push the left child on queue
  50.                 if (Node.left != null) {
  51.                     Q.add(Node.left);
  52.                 }
  53.                
  54.                 // push the right child on queue
  55.                 if (Node.right != null) {
  56.                     Q.add(Node.right);
  57.                 }
  58.                 count -= 1;
  59.             }
  60.         }
  61.        
  62.         // return the final width
  63.         return result;
  64.     }
  65.    
  66.     public static void main(String arg[]) {
  67.         node head = new node(1);
  68.         head.left = new node(2);
  69.         head.right = new node(3);
  70.         head.left.left = new node(4);
  71.         head.left.right = new node(5);
  72.         head.right.right = new node(6);
  73.         head.left.left.right = new node(7);
  74.         head.right.right.left = new node(8);
  75.         head.left.left.right.left = new node(9);
  76.         head.left.left.right.left.left = new node(10);
  77.         head.right.right.left.right = new node(11);
  78.         System.out.print("Width of the above binary tree is : " + width(head));
  79.        
  80.     }
  81. }
Add Comment
Please, Sign In to add comment