Width of a Binary Tree

Width of a binary tree is defined as maximum number of nodes present at any level of the given tree.

Java Implementation of finding Width of a Binary Tree

import java.util.LinkedList;
import java.util.Queue;

class Solution
{
    static class TreeNode{
        int data;
        TreeNode left,right;
        TreeNode(int data)
        {
            this.data=data;
        }
    }
    static int WidthOfBinaryTree(TreeNode root)
    {
        int width=0;
        Queue<TreeNode> queue=new LinkedList<>();
        queue.add(root);
        
        while(!queue.isEmpty())
        {
            int queueSize=queue.size();
            if(queueSize>width)
                width=queueSize;
            for(int i=0;i<queueSize;i++)
            {
                TreeNode temp=queue.poll();
                if(temp.left!=null)
                    queue.add(temp.left);
                if(temp.right!=null)
                    queue.add(temp.right);
            }
        }
        return width;
    }
     public static void main(String[] args)
    {
        TreeNode root=new TreeNode(1);
        root.left=new TreeNode(2);
        root.right=new TreeNode(3);
        root.left.left=new TreeNode(4);
        root.left.right=new TreeNode(5);
        int width=WidthOfBinaryTree(root);
        System.out.println("Width is equal to "+width);
    }
    }

Output: Width is equal to 2

Time Complexity- O(n)

Space Complexity- O(n)

Leave a comment

Your email address will not be published. Required fields are marked *

Pin It on Pinterest