# 二叉树的最大深度|博客系列

> 本文详细讲解了如何计算二叉树的最大深度，包括题目描述、解题思路和JavaScript代码实现，适合数据结构与算法学习者参考。

- 原文：https://feinterview.poetries.top/docs/fe-blog-docs/blog-docs/data-struct/13-%E4%BA%8C%E5%8F%89%E6%A0%91%E7%9A%84%E6%9C%80%E5%A4%A7%E6%B7%B1%E5%BA%A6
- 来源：前端进阶之旅（feinterview.poetries.top）
- 更新：2025.10.25

---

## 二叉树的最大深度

### 题目描述

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

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

### 解题思路

1. 深度遍历二叉树，比较出左子树的最大深度和右子树的最大深度
2. 二叉树的最大深度为上面比较的结果 + 1.

### coding

**解法一**: 较为复杂

实现上和 [二叉搜索树的第k个节点](./二叉搜索树的第k个节点.md)有点类似：

```javascript
class Tree {
    constructor(value = 0, left = null, right = null) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
}
function getMaxDeep(tree) {
    if (!tree) return 0;
    let deep = 0, // 定义一个路径的深度
        maxDeep = 0; // 定义最大的深度
    function _getMaxDeep(node) {
        if (!node) return; // 若是没有节点则直接返回
        deep++;
        let isLeaf = !node.left && !node.right; // 判断是否是叶子节点
        if (isLeaf && deep > maxDeep) { // 若是叶子节点且当前路径的深度大于最大的深度
            maxDeep = deep;
        }
        if (node.left) { // 若是有左子树节点则遍历
            _getMaxDeep(node.left)
        }
        if (node.right) {
            _getMaxDeep(node.right)
        }
        deep--; // 遍历完之后将deep重置
    }
    _getMaxDeep(tree);
    return maxDeep;
}

const tree = new Tree(1, new Tree(2, new Tree(4), new Tree(6, new Tree(7))), new Tree(3, null, new Tree(5)));
console.log(getMaxDeep(tree))
// 4

```

**解法二**：简单明了

```javascript
function treeDepth (node) {
    return !node ? 0 : Math.max(treeDepth(node.left), treeDepth(node.right)) + 1;
}
const tree = new Tree(1, new Tree(2, new Tree(4), new Tree(6, new Tree(7))), new Tree(3, null, new Tree(5)));
console.log(treeDepth(tree))
// 4
```
