废话不多说,二叉树概念的基础. 直接用后序遍历,两行代码搞定. 代码如下:

1
2
3
4
5
6
7
8
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
return max(self.maxDepth(root.left),
self.maxDepth(root.right)) + 1