Width of a Binary Tree :

It is defined as maximum number of nodes present at any level in the binary tree.

Java Code

import java.util.*;

class Node{
int data;
Node left,right;
Node(int d)
{
data=d;
left=right=null;
}
}

public class width {
Node root;
int getWidth(Node root)
{
LinkedList<Node> q=new LinkedList<Node>(); //queue 
q.add(root);

int max_width=0;

while(!q.isEmpty())
{
int width=q.size();  //this will check number of nodes at current level
      
if(width>max_width)
max_width=width;

while(width-->0) // we add all nodes present in next level in this while loop
{
Node temp=q.removeFirst();

if(temp.left!=null)
q.add(temp.left);
if(temp.right!=null)
q.add(temp.right);
}

}
return max_width;
}
public static void main(String[] args)
{
width tree=new width();
tree.root=new Node(1);
tree.root.left=new Node(2);
tree.root.right=new Node(3);
tree.root.left.left=new Node(4);
tree.root.left.right=new Node(5);
tree.root.right.left=new Node(6);
tree.root.left.left.left=new Node(7);
tree.root.left.left.left.left=new Node(11);
tree.root.left.left.left.left.left=new Node(12);
tree.root.right.right=new Node(8);

int w=tree.getWidth(tree.root);
System.out.println(w);
}
}

Output :  4

Pin It on Pinterest