maxDepth 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 maxDepth = function(root) {
        return (root) ? Math.max(maxDepth(root.left), maxDepth(root.right)) + 1 : 0;
    };
    

  • 0
    S

    Hey,
    My solution is almost identical to yours. I've just used a separate function call to make it more readable. I do have one feedback though. The question, and hence our solution only works for a binary tree. I'd recommend updating the title of your post to include that.

    Here's my recursive solution for anyone interested:

    var maxDepth = function(root) {
        return traverse(root, 0);
    };
    function traverse(root, depth){
        return !root ? depth : Math.max(traverse(root.left, depth+1), traverse(root.right, depth+1));   
    }
    

Log in to reply
 

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