My accepted [1 ms] BFS solution (Java)


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

Log in to reply
 

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