题目:
Given the root of a binary tree, return its maximum depth.
A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
给定一个binary tree,算它的最大深度
刚看到还以为有点複杂,结果做起来程式码有够精简XD
# 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 = rightclass Solution: def maxDepth(self, root: Optional[TreeNode]) -> int: if not root: return 0 return max(self.maxDepth(root.left),self.maxDepth(root.right))+1
如果是None代表跑到树外了(底层之外),回传0(树外不算一层)
若非None则回传左右节点向下探索后较深的一侧的深度+1(算上自己这层的深度)
值不断+1回传直到root,我们便得到了此树的最大深度
最后执行时间39ms(faster than 96.86%)
那我们下题见