
👨💻 关于作者:会编程的土豆
"不是因为看见希望才坚持,而是坚持了才看见希望。"
你好,我是会编程的土豆,一名热爱后端技术的Java学习者。
📚 正在更新中的专栏:
-
《数据结构与算法》😊😊😊
-
《leetcode hot 100》🥰🥰🥰🤩🤩🤩
-
《数据库mysql》
💕作者简介:后端学习者
1.

cpp
#include<iostream>
using namespace std;
const int MAXN = 1e6 + 5;
int leftchild[MAXN];
int rightchild[MAXN];
int n;
int getdepth(int node)
{
if (node == 0) return 0;
int leftdepth = getdepth(leftchild[node]);
int rightdepth = getdepth(rightchild[node]);
return max(leftdepth, rightdepth)+1;
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> leftchild[i] >> rightchild[i];
}
int ans = getdepth(1);
cout << ans;
return 0;
}
用数组表示二叉树并求最大深度:从原理到代码一篇讲透
这道题是二叉树最基础、也是最重要的能力之一:
👉 求二叉树的最大深度(高度)
你这份代码写法很典型:数组建树 + 递归DFS求深度 。
这篇文章我帮你把每一部分都讲清楚,保证你不仅会写,还知道为什么这么写。
一、问题本质
输入:
n(节点个数)
接下来 n 行:
每个节点的 左孩子 和 右孩子
例如:
5
2 3
4 5
0 0
0 0
0 0
表示:
1
├── 2
│ ├── 4
│ └── 5
└── 3
二、数组建树(核心思想)
int leftchild[MAXN];
int rightchild[MAXN];
含义
leftchild[i] → 节点 i 的左孩子
rightchild[i] → 节点 i 的右孩子
关键点
用"编号"代替指针
特殊值
0 表示:没有子节点(空节点)
三、什么是树的深度?
定义:
从根节点到最远叶子节点的路径长度
举例
1
/ \
2 3
/
4
最大深度:
3
四、核心函数解析(DFS)
int getdepth(int node)
{
if (node == 0) return 0;
int leftdepth = getdepth(leftchild[node]);
int rightdepth = getdepth(rightchild[node]);
return max(leftdepth, rightdepth) + 1;
}
这段代码在干什么?
一句话:
递归计算左右子树深度,取最大值 + 1
执行逻辑拆解
递归终止条件
if (node == 0) return 0;
空节点深度为 0
递归计算左右子树
int leftdepth = getdepth(leftchild[node]);
int rightdepth = getdepth(rightchild[node]);
返回当前节点深度
return max(leftdepth, rightdepth) + 1;
当前节点 = 子树最大深度 + 自己这一层
五、完整执行流程(举例)
树:
1
├── 2
│ ├── 4
│ └── 5
└── 3
计算过程
getdepth(1)
→ max(getdepth(2), getdepth(3)) + 1
getdepth(2)
→ max(getdepth(4), getdepth(5)) + 1
getdepth(4) → 1
getdepth(5) → 1
getdepth(2) → 2
getdepth(3) → 1
最终:3
六、主函数解析
for (int i = 1; i <= n; i++)
{
cin >> leftchild[i] >> rightchild[i];
}
含义
节点编号就是 1 ~ n
默认根节点是 1
求答案
int ans = getdepth(1);
七、时间复杂度
O(n)
原因:
每个节点只访问一次
八、空间复杂度
O(n)
来源:
-
递归栈
-
数组存储
九、常见错误
1. 忘记处理 node == 0
会导致:
递归爆炸 / 访问非法
2. 根节点写错
getdepth(1);
👉 前提是:题目保证 1 是根
3. 输入理解错误
输入的是"编号",不是值
十、进阶写法(非递归 BFS)
如果不想用递归,也可以用层序遍历:
// 用队列按层遍历,统计层数
适合:
防止递归爆栈
十一、一句话总结
树的深度 = max(左子树深度, 右子树深度) + 1