leetcode 559. Maximum Depth of N-ary Tree
Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
For example, given a 3-ary
tree:
We should return its max depth, which is 3.
Note:
- The depth of the tree is at most
1000
. - The total number of nodes is at most
5000
.
DFS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | """ # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children """ class Solution( object ): def maxDepth( self , root): """ :type root: Node :rtype: int """ if not root: return 0 if not root.children: return 1 depths = [ self .maxDepth(node) for node in root.children] return max (depths) + 1 |
简化下,
1 2 3 4 5 | class Solution( object ): def maxDepth( self , root): if not root: return 0 if not root.children: return 1 return max ( self .maxDepth(node) for node in root.children) + 1 |
或者是:
1 2 3 | class Solution( object ): def maxDepth( self , root): return 1 + max ([ self .maxDepth(n) for n in root.children] + [ 0 ]) if root else 0 |
BFS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | """ # Definition for a Node. class Node(object): def __init__(self, val, children): self.val = val self.children = children """ class Solution( object ): def maxDepth( self , root): """ :type root: Node :rtype: int """ if not root: return 0 ans = 0 q = [root] while q: ans + = 1 q = [c for node in q for c in node.children if c] return ans |
标签:
leetcode
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
2017-07-21 pyspark MLlib踩坑之model predict+rdd map zip,zip使用尤其注意啊啊啊!
2017-07-21 高斯混合模型Gaussian Mixture Model (GMM)——通过增加 Model 的个数,我们可以任意地逼近任何连续的概率密分布