104. 二叉树的最大深度
1.题目
2.我的解决方案
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: TreeNode) -> int:
ld, rd = 0, 0
if not root: # 空树
return 0
if not root.left and not root.right: # 叶子结点
return 1
if root.left:
ld = self.maxDepth(root.left) + 1
if root.right:
rd = self.maxDepth(root.right) + 1
return max(ld, rd)
3.官方的解决方案
- 直接记忆
class Solution:
def maxDepth(self, root):
if root is None:
return 0
else:
left_height = self.maxDepth(root.left)
right_height = self.maxDepth(root.right)
return max(left_height, right_height) + 1