leetcode104 二叉树的最大深度

114 阅读2分钟

给定一个二叉树 root ,返回其最大深度。

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

示例 1:

输入: root = [3,9,20,null,null,15,7]
输出: 3

示例 2:

输入: root = [1,null,2]
输出: 2

方法一:深度优先

运用递归,判断当前节点是否存在,不存在则深度为零,存在则深度 = 最深子树的深度+1。

/**
 * 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
    }else{
        // 存在,则深度为最深的子树+1
        return Math.max( maxDepth(root.left),maxDepth(root.right) ) +1
    }
};

方法二:广度优先

根节点存放队列中(队列表示当前层的节点),循环遍历队列(直到当前层的节点没有了,既最后一层也遍历完了),再遍历每个节点(从队列中取出一个节点,然后将其左右节点入队,这样最后队列保存的就是这一层的所有节点了),然后层数累加,直到没有层了。

/**
 * 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;}  // 如果根节点为空,直接返回深度 0
    const queue = [];               // 创建一个队列,用于存储待遍历的节点
    queue.push(root);               // 将根节点入队
    let depth = 0;                  // 初始化深度为 0
    while (queue.length > 0) {      // 循环遍历队列中的节点,直到队列为空
        const size = queue.length;  // 获取当前队列的大小,即当前层的节点数
        for (let i = 0; i < size; i++) {    // 遍历当前层的节点
            const node = queue.shift();      // 从队列中取出一个节点
            // 如果该节点存在左子节点,将左子节点入队
            if (node.left !== null) {queue.push(node.left);}
            // 如果该节点存在右子节点,将右子节点入队
            if (node.right !== null) {queue.push(node.right);}
        }
        // 遍历完一层节点后,深度加一
        depth++;
    }
    return depth;
};

链接:leetcode.cn/problems/lo…

来源:力扣(LeetCode)