Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // http://code2begin.blogspot.com
- // program to print width of a given binary tree
- /**
- * Created by MOHIT on 25-05-2018.
- */
- import java.util.*;
- // node class
- class node{
- int data;
- node left;
- node right;
- // function that returns a pointer to new node
- public node(int element){
- this.data = element;
- this.left = null;
- this.right = null;
- }
- };
- public class BinaryTree {
- // function to print the width of the binary tree
- static int width(node root){
- if(root == null){
- return 0 ;
- }
- // creating a Queue for storing node for level wise traversal
- ArrayList Q = new ArrayList<node>();
- Q.add(root);
- int result = 0;
- while(!Q.isEmpty()){
- // store the current size of the Q
- int count = Q.size();
- // find out the max width
- result = max(result, count);
- while(count > 0) {
- // pop the first node from the queue
- node Node = (node)Q.get(0);
- Q.remove(0);
- // push the left child on queue
- if (Node.left != null) {
- Q.add(Node.left);
- }
- // push the right child on queue
- if (Node.right != null) {
- Q.add(Node.right);
- }
- count -= 1;
- }
- }
- // return the final width
- return result;
- }
- public static void main(String arg[]) {
- node head = new node(1);
- head.left = new node(2);
- head.right = new node(3);
- head.left.left = new node(4);
- head.left.right = new node(5);
- head.right.right = new node(6);
- head.left.left.right = new node(7);
- head.right.right.left = new node(8);
- head.left.left.right.left = new node(9);
- head.left.left.right.left.left = new node(10);
- head.right.right.left.right = new node(11);
- System.out.print("Width of the above binary tree is : " + width(head));
- }
- }
Add Comment
Please, Sign In to add comment