My Accepted Java Solution using Deque


  • 1
    H
    public int widthOfBinaryTree(TreeNode root) {
            if(root==null)
                return 0;
            Deque<TreeNode> q=new LinkedList<>();
            q.add(root);
            int max=0;
            while(!q.isEmpty()){
                int count=0;
                max=Math.max(max,q.size());
                int size=q.size();
                while(count<size){
                    TreeNode node=q.poll();
                    if(node==null){
                        q.add(null);q.add(null);
                    }else{
                        q.add(node.left);q.add(node.right);
                    }
                    count++;
                }
                while(!q.isEmpty()&&q.peekFirst()==null)
                    q.pollFirst();
                while(!q.isEmpty()&&q.peekLast()==null)
                    q.pollLast();
            }
            return max;
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.