日野弥生:勉強しよう
LeetCode 104 - 二叉树的最大深度
发表于2025年02月17日
按照自顶向下的设计思路,即“前序遍历”的思想,先处理根节点,然后传递给左右子树。当根节点无左右子树时,更新深度值。当根结点有子树时,传递深度给左右子树。
class Solution:
def maxDepthImpl(self, root: Optional[TreeNode], depth: [int]):
if root is None:
return
if root.left is None and root.right is None:
self.result = max(self.result, depth)
self.maxDepthImpl(root.left, depth + 1)
self.maxDepthImpl(root.right, depth + 1)
def maxDepth(self, root: Optional[TreeNode]) -> int:
self.result = 0
self.maxDepthImpl(root, 1)
return self.result
如果按照自底向上的设计理念,即“后序遍历”的思想。先利用递归计算出两个子树的深度,然后对根节点进行取最大值后加1,即可得到结果。
class Solution:
def calculateDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
leftDepth = self.calculateDepth(root.left)
rightDepth = self.calculateDepth(root.right)
return max(leftDepth, rightDepth) + 1