Java, Iterative Solution, concise and easy understanding


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

    }


  • 0
    T

    What's the point of the min variable? Is it a residue from an earlier version when you traversed the whole tree and investigated every leaf?

    It is assigned only once, which means that the return value is equivalent to return Math.min(Integer.MAX_VALUE, level) which is the same as return level.

    Also that if with return 1 is included in the logic below.


  • 0
    B

    I do the BFS and use min to refer as level(or the height), if I first hit a leaf node in a specific level, then this level must be at the minimum depth. Just use min as a recorder. Or maybe we can just return the min value once we hit a leaf node


  • 0
    T

    Yes, the second part. Since BFS goes level-by-level the first leaf node you find is the answer.
    Notice that you return immediately after min=, so it won't ever be seen again.


Log in to reply
 

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