[路飞]_LeetCode_104. 二叉树的最大深度

119 阅读1分钟

题目

给定一个二叉树,找出其最大深度。

二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。

说明: 叶子节点是指没有子节点的节点。

示例: 给定二叉树 [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回它的最大深度 3 。

来源:力扣(LeetCode)leetcode-cn.com/problems/ma…

解题思路

这道题有广度优先和深度优先两种解法,分别对应着循环和递归,递归的解法代码教简洁。这里我们用队列的方式,一层一层统计深度。

代码实现

var maxDepth = function(root) {
    if (!root) return 0;
    
    const queue = [root]
    let dep = 0

    while(queue.length) {
        const len = queue.length
        for (let i = 0; i < len; i++) {
            const node = queue.shift()
            if (node.left) queue.push(node.left)
            if (node.right) queue.push(node.right)
        }
        dep++
    }

    return dep
};

如有错误欢迎指出,欢迎一起讨论!