JavaScript Solution with explanation


  • 0
    I
    var minDepth = function (root) {
        if (!root) return 0;
        let min = Infinity;
        function iterate(node, level) {
            //check if the node is a leaf node
            if (!node.left && !node.right) {
                if (level < min) {
                    min = level;
                }
                return;
            }
            level++;
            //check level < min to skip some iterations
            if (node.left && level < min) {
                iterate(node.left, level);
            }
            if (node.right && level < min) {
                iterate(node.right, level);
            }
        }
        iterate(root, 0);
        //level 0 is actually the first level
        return ++min;
    };
    

Log in to reply
 

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