minDepth of tree with JavaScript


  • 0
    N
    /**
     * Definition for a binary tree node.
     * function TreeNode(val) {
     *     this.val = val;
     *     this.left = this.right = null;
     * }
     */
    /**
     * @param {TreeNode} root
     * @return {number}
     */
    var minDepth = function(root) {
        if(!root) {
            return 0;
        }
        
        let leftDepth = (root.left) ? minDepth(root.left) : 0;
        let rightDepth = (root.right) ? minDepth(root.right) : 0;
        
        return (leftDepth === 0 || rightDepth === 0) ? leftDepth + rightDepth + 1 : Math.min(leftDepth, rightDepth) + 1;
    };
    

Log in to reply
 

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