1 + max(left, right) 递归。
OJ: leetcodecn
题目 ID: maximum-depth-of-binary-tree
难度:入门
标签:二叉树递归BFScpppython
日期: 2026-07-28 22:05
题意
返回二叉树的最大深度(根到最远叶子节点的路径长度)。
思路
递归:空节点深度 0,非空节点深度 = 1 + max(左子树深度, 右子树深度)。
BFS 层序遍历也可以统计深度。
代码
cpp
/**
* Author by Rainboy
*/
#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
class Solution {
public:
int maxDepth(TreeNode *root) {
if (!root)
return 0;
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
TreeNode *build(istream &in, int n) {
if (!n)
return nullptr;
vector<TreeNode *> nodes(n);
for (int i = 0, v; i < n; i++) {
in >> v;
if (v != -1)
nodes[i] = new TreeNode(v);
}
for (int i = 0; i < n; i++) {
if (!nodes[i])
continue;
int l = 2 * i + 1, r = 2 * i + 2;
if (l < n)
nodes[i]->left = nodes[l];
if (r < n)
nodes[i]->right = nodes[r];
}
return nodes[0];
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
auto root = build(cin, n);
cout << Solution().maxDepth(root) << '\n';
return 0;
}python
#!/usr/bin/env python3
from typing import Optional
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if not root:
return 0
return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right))
def build(arr):
if not arr:
return None
nodes = [TreeNode(v) if v != -1 else None for v in arr]
for i in range(len(nodes)):
if nodes[i] is None:
continue
l, r = 2 * i + 1, 2 * i + 2
if l < len(nodes):
nodes[i].left = nodes[l]
if r < len(nodes):
nodes[i].right = nodes[r]
return nodes[0]
def main() -> None:
n = int(input())
a = list(map(int, input().split()))
root = build(a)
print(Solution().maxDepth(root))
if __name__ == "__main__":
main()复杂度
- 时间复杂度:O(n)。
- 空间复杂度:O(height) 递归栈。
总结
树的最大深度是树形 DP 的最简单例子——通过子问题定义"以某节点为根的子树深度"。