104二叉树的最大深度
def maxDepth(self, root):return self.getdepth(root)
- 直接调用
getdepth
方法计算根节点的最大深度
getdepth方法
def getdepth(self, node):if not node: # 基准情况:空节点深度为0return 0leftheight = self.getdepth(node.left) # 递归计算左子树深度rightheight = self.getdepth(node.right) # 递归计算右子树深度height = 1 + max(leftheight, rightheight) # 当前节点深度 = 1 + 左右子树最大深度
return height
具体例子
考虑以下二叉树:
递归计算过程
- 从根节点3开始:
- 计算左子树9的深度:
- 9是叶子节点,left=right=0 → 深度=1
- 计算右子树20的深度:
- 20的左子树15:
- 15是叶子节点 → 深度=1
- 20的右子树7:
- 7是叶子节点 → 深度=1
- 20的深度 = 1 + max(1,1) = 2
- 20的左子树15:
- 根节点3的深度 = 1 + max(1,2) = 3
- 计算左子树9的深度:
递归调用栈图示
再举一个例子:
我们调用 maxDepth(1)
,它会执行 getdepth(1)
,然后递归计算每个子树的深度。
步骤 1:计算 getdepth(1)
1
不是None
,继续执行。- 计算
getdepth(1.left)
→getdepth(2)
(左子树) - 计算
getdepth(1.right)
→getdepth(3)
(右子树) - 最终返回
1 + max(左子树深度, 右子树深度)
步骤 2:计算 getdepth(2)
2
不是None
,继续执行。- 计算
getdepth(2.left)
→getdepth(4)
(左子树) - 计算
getdepth(2.right)
→getdepth(5)
(右子树) - 返回
1 + max(左子树深度, 右子树深度)
步骤 3:计算 getdepth(4)
4
不是None
,继续执行。4.left
是None
→getdepth(None)
返回0
4.right
是None
→getdepth(None)
返回0
- 返回
1 + max(0, 0) = 1
(4
是叶子节点)
步骤 4:计算 getdepth(5)
5
不是None
,继续执行。5.left
是6
→getdepth(6)
(左子树)5.right
是None
→getdepth(None)
返回0
- 返回
1 + max(左子树深度, 0)
步骤 5:计算 getdepth(6)
6
不是None
,继续执行。6.left
是None
→getdepth(None)
返回0
6.right
是None
→getdepth(None)
返回0
- 返回
1 + max(0, 0) = 1
(6
是叶子节点)
步骤 6:回代计算 getdepth(5)
getdepth(5)
的左子树深度 = getdepth(6) = 1
getdepth(5)
的右子树深度 = 0
- 返回
1 + max(1, 0) = 2
步骤 7:回代计算 getdepth(2)
getdepth(2)
的左子树深度 = getdepth(4) = 1
getdepth(2)
的右子树深度 = getdepth(5) = 2
- 返回
1 + max(1, 2) = 3
步骤 8:计算 getdepth(3)
3
不是None
,继续执行。3.left
是None
→getdepth(None)
返回0
3.right
是None
→getdepth(None)
返回0
- 返回
1 + max(0, 0) = 1
(3
是叶子节点)
步骤 9:回代计算 getdepth(1)
getdepth(1)
的左子树深度 = getdepth(2) = 3
getdepth(1)
的右子树深度 = getdepth(3) = 1
- 返回
1 + max(3, 1) = 4
最终结果
maxDepth(1)
返回4
,即该二叉树的最大深度。
递归调用栈总结
递归调用 | 左子树深度 | 右子树深度 | 返回结果 |
---|---|---|---|
getdepth(6) | 0 | 0 | 1 + max(0, 0) = 1 |
getdepth(5) | getdepth(6)=1 | 0 | 1 + max(1, 0) = 2 |
getdepth(4) | 0 | 0 | 1 + max(0, 0) = 1 |
getdepth(2) | getdepth(4)=1 | getdepth(5)=2 | 1 + max(1, 2) = 3 |
getdepth(3) | 0 | 0 | 1 + max(0, 0) = 1 |
getdepth(1) | getdepth(2)=3 | getdepth(3)=1 | 1 + max(3, 1) = 4 |
关键点
- 递归终止条件:当
node
是None
时,返回0
(表示空树的深度为 0)。 - 递归分解问题:
- 计算
左子树的深度
- 计算
右子树的深度
- 当前节点的深度 =
1 + max(左子树深度, 右子树深度)
- 计算
- 最终结果:根节点的深度就是整棵树的最大深度。