应用题-二叉树专题-二叉树的最大深度

管理员
**写法1** ```python # 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: self.max_h = 0 def maxDepth_( r, h ): if not r: return if h > self.max_h: self.max_h = h maxDepth_( r.left, h + 1 ) maxDepth_( r.right, h + 1 ) maxDepth_( root, 1 ) return self.max_h ``` **写法2** ```python # 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: if not root: return 0 h1 = self.maxDepth( root.left ) h2 = self.maxDepth( root.right ) return max( h1, h2 ) + 1 ```
评论 0

发表评论 取消回复

Shift+Enter 换行  ·  Enter 发送
还没有评论,来发表第一条吧