Skip to content

104. 二叉树的最大深度

leetCode-104. 二叉树的最大深度

BFS

js
/**
 * 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) {
    let maxDepth = 0
    // 树为空的时候
    if (root === null) return maxDepth
    // 定义一个队列
    let queue = []
    let count = 0
    queue.push(root)
    while (queue.length > 0) {
        // 获取这一层的长度
        let size= queue.length
        // 遍历这一层的内容
        while (size > 0){
            let node = queue.shift()
            size--
            if(node.left || node.right) {
                if(node.left !== null) queue.push(node.left)
                if(node.right !== null) queue.push(node.right)
            }
        }
        maxDepth++
    }
    return maxDepth
};

DFS

js
/**
 * 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 === null) return 0
    let leftDep = maxDepth(root.left)
    let rightDep = maxDepth(root.right)
    return Math.max(leftDep, rightDep)+1
};

MIT Licensed