m2skills

right view iter java

Jul 24th, 2018
821
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.25 KB | None | 0 0
  1. // http://code2begin.blogspot.com
  2. // program to print the right view of a given binary tree iteratively
  3.  
  4. /**
  5.  * Created by MOHIT on 25-05-2018.
  6.  */
  7.  
  8. import java.util.*;
  9. import static java.lang.Integer.max;
  10.  
  11. // node class
  12. class node{
  13.     int data;
  14.     node left;
  15.     node right;
  16.  
  17.     // function that returns a pointer to new node
  18.     public node(int element){
  19.         this.data = element;
  20.         this.left = null;
  21.         this.right = null;
  22.        
  23.     }
  24. };
  25.  
  26.  
  27. public class BinaryTree {
  28.  
  29.     // BFS iterative using queue for right view
  30.     static void right_view_iter(node root){
  31.         if(root == null){
  32.             return;
  33.         }
  34.  
  35.         // creating a Queue for storing node for level wise traversal
  36.         ArrayList Q = new ArrayList<node>();;
  37.         Q.add(root);
  38.         int level = 0, max_level = 0;
  39.  
  40.         while(!Q.isEmpty()){
  41.             // store the current size of the Q
  42.             int count = Q.size();
  43.             level += 1;
  44.             while(count > 0) {
  45.                 // pop the first node from the queue
  46.                 node NODE = (node)Q.get(0);
  47.                 Q.remove(0);
  48.                 if(max_level < level) {
  49.                     System.out.print(NODE.data + " ");
  50.                     max_level = level;
  51.                 }
  52.  
  53.                 // push the right child on queue
  54.                 if (NODE.right != null) {
  55.                     Q.add(NODE.right);
  56.                 }
  57.  
  58.                 // push the left child on queue
  59.                 if (NODE.left != null) {
  60.                     Q.add(NODE.left);
  61.                 }
  62.                 count--;
  63.             }
  64.         }
  65.     }
  66.      
  67.     public static void main(String arg[]) {
  68.         node head = new node(1);
  69.         head.left = new node(2);
  70.         head.right = new node(3);
  71.         head.left.left = new node(4);
  72.         head.left.right = new node(5);
  73.         head.right.right = new node(6);
  74.         head.left.left.right = new node(7);
  75.         head.right.right.left = new node(8);
  76.         head.left.left.right.left = new node(9);
  77.         head.left.left.right.left.left = new node(10);
  78.         head.right.right.left.right = new node(11);
  79.         System.out.print("Right view of the binary tree is : ");
  80.         right_view_iter(head);
  81.     }
  82. }
Add Comment
Please, Sign In to add comment