二叉树最大深度(python)

递归

具体做法:

  • step 1:对于每个节点,若是不为空才能累计一次深度,若是为空,返回深度为0.
  • step 2:递归分别计算左子树与右子树的深度。
  • step 3:当前深度为两个子树深度较大值再加1。
def maxDepth(self , root: TreeNode) -> int:
        # write code here
        # 空节点没有深度
        if not root:
            return 0
        # 返回子树深度+1
        return max([self.maxDepth(root.left), self.maxDepth(root.right)]) + 1
posted @ 2022-12-01 18:50  小仙女、  阅读(150)  评论(0)    收藏  举报