简单的递归实现即可。
# 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: Optional[TreeNode]) -> int:
depth = self.dfs(root) # 根的节点高度为0
return depth
def dfs(self,root):
if root is None:
return 0
left_depth = self.dfs(root.left)
right_depth = self.dfs(root.right)
return max(left_depth,right_depth) + 1