leetcode with python:104. Maximum Depth of Binary Tree

题目:

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%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章