37.二叉树的最大深度

170 阅读1分钟

题目链接

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

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

解法1 递归dfs

思路

像二叉树的一些题目都可以用递归的思路去解题。

递归首先想到的是停止条件,如果当前节点没有左右子树,那么深度为 1 直接返回即可。

接下来对左子树和右子树递归计算深度,返回时返回左右子树中最大的高度再加上这一层的高度 1 即可。

代码

function maxDepth(root: TreeNode | null): number {
    if (!root) {
        return 0;
    }
    if (!root.left && !root.right) {
        return 1;
    }
    const left = root.left ? maxDepth(root.left) : 0;
    const right = root.right ? maxDepth(root.right) : 0;

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

时空复杂度

时间复杂度:O(n)

空间复杂度:平均O(h)h 是树的高度。最差退化为单链表 栈空间为 O(n)

解法2 层序遍历bfs

思路

将每一层的子节点放入队列中,逐个遍历,最大深度自增。

代码

function maxDepth(root: TreeNode | null): number {
    if (root === null) return 0;

    let queue: TreeNode[] = [root];
    let depth = 0;

    while (queue.length > 0) {
        const levelSize = queue.length;

        for (let i = 0; i < levelSize; i++) {
            const node = queue.shift()!;
            if (node.left) queue.push(node.left);
            if (node.right) queue.push(node.right);
        }

        depth++;
    }

    return depth;
};

时空复杂度

时间复杂度:O(n)

空间复杂度:O(n)