harrytothemoon / leetcodeAplus

Leetcode meeting note
2 stars 0 forks source link

[104] Maximum Depth of Binary Tree #55

Open tsungtingdu opened 4 years ago

tsungtingdu commented 4 years ago
var maxDepth = function(root) {
    if (root === null) return 0
    return traverse(root, 1)

    function traverse(node, count){
        if(node.left === null && node.right === null) return count

        let leftCount = count
        let rightCount = count

        if (node.left !== null) leftCount = traverse(node.left, count + 1)
        if (node.right !== null) rightCount = traverse(node.right, count + 1)

        return Math.max(leftCount, rightCount)
    }

};
ShihTingJustin commented 4 years ago
var maxDepth = function(root) {
    // edge case
    if (root === null) return 0
    if (root.left === null && root.right === null) return 1

    let ans = Number.MIN_SAFE_INTEGER
    if (root.left !== null) ans = Math.max(maxDepth(root.left), ans)
    if (root.right !== null) ans = Math.max(maxDepth(root.right), ans)
    return ans + 1
};
harrytothemoon commented 4 years ago
var maxDepth = function(root) {
    if (!root)  return 0;
    let depth = 0
    let queue = [root]
    while (queue.length) {
        let len = queue.length
        for (let i = 0; i < len; i++) {
            let node = queue.shift()
            if (node === null) return 0
            if (node.left !== null) queue.push(node.left)
            if (node.right !== null) queue.push(node.right)
        }
        depth++
    }
    return depth
};
henry22 commented 4 years ago
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var maxDepth = function(root) {
    if(!root) {
        return 0
    }

    return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1
};