BFS is better than DFS for solving this problem, and one queue is enough.


  • 0
    B
        public int minDepth(TreeNode root) {
            if (root == null) {
                return 0;
            }
            Deque<TreeNode> queue = new LinkedList<>();
            queue.addLast(root);
            int depth = 0;
            while (!queue.isEmpty()) {
                depth++;
                int size = queue.size();
                while (size > 0) {
                    TreeNode cur = queue.pollFirst();
                    if (cur.left == null && cur.right == null) {
                        return depth;
                    } 
                    if (cur.left != null) {
                        queue.addLast(cur.left);
                    } 
                    if (cur.right != null) {
                        queue.addLast(cur.right);
                    }
                    size--;
                }
            }
            return depth;
        }
    }
    

    BFS will traverse minimum numbers of TreeNode.


Log in to reply
 

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