My BFS java solution


  • 1
    public int minDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int level = 1;
        
        while(! queue.isEmpty()){
            int nodeNum = queue.size();
            
            for(int i = 0; i < nodeNum; i ++){
                TreeNode cur = queue.poll();
                
                if(cur.left == null && cur.right == null){
                    return level;
                }
                
                if(cur.left != null){
                    queue.offer(cur.left);
                }
                
                if(cur.right != null){
                    queue.offer(cur.right);
                }
            }
            
            level ++;
        }
        
        return 0;
    

    }


Log in to reply
 

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