My 2ms java solution using BFS


  • 0
    S
    public class Solution {
        public int minDepth(TreeNode root) {
            if(root==null)
                return 0;
            Deque<TreeNode> queue=new ArrayDeque<TreeNode>();
            int depth=0;
            queue.offer(root);
            while(!queue.isEmpty()){
                boolean flag=false;
                depth++;
                int len=queue.size();
                int count=0;
                while(count<len){
                    TreeNode p=queue.poll();
                    if(p.left!=null)
                        queue.offer(p.left);
                    if(p.right!=null)
                        queue.offer(p.right);
                    count++;
                    if(p.right==null&&p.left==null)
                        flag=true;
                }
                if(flag==true)
                    break;
               
            }
            return depth;
        }
    }

Log in to reply
 

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