怎样计算二叉树的深度?
先说出你的答案
定义边界、关键机制、一个反例;P8题再补容量、失败与验证。
查看完整题解
参考回答
直接回答
这里把深度结果按节点层数计,空树为 0,单节点为 1。递归公式是 1+max(左深度,右深度)。非递归可做分层 BFS,处理完一层将深度加一。
讲清原理
两种方法时间都是 O(n)。递归辅助空间 O(h),BFS 队列 O(w)。窄而很深的树与矮而很宽的树,适合的空间取舍不同。
例子与易错点
例如根到最深叶经过 4 个节点,返回 4;若题目按边数定义高度,则非空树结果减一。测试前先统一口径,避免最大距离题与本题混用。
下面是 Java 21 类成员片段,可放入同一个工具类。
static final class Node {
int value;
Node left;
Node right;
Node(int value) { this.value = value; }
}
static int depth(Node root) {
return root == null ? 0 : 1 + Math.max(depth(root.left), depth(root.right));
}
static int depthBfs(Node root) {
var queue = new java.util.ArrayDeque<Node>();
if (root != null) queue.offer(root);
int height = 0;
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 0; i < size; i++) {
Node node = queue.remove();
if (node.left != null) queue.offer(node.left);
if (node.right != null) queue.offer(node.right);
}
height++;
}
return height;
}
相关题:第 15 题、第 43 题、第 49 题。
和评分标准对照,你能独立回答到哪一步?
自评会安排下一次复习,不保存你的口述内容。
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。