559.N叉树的大深度(javascript)559.MaximumDepthofN-aryTree
原创给定一个 N 叉树,找到它的最大深度。
最大深度是指从根节点到最远叶节点的最长路径上的节点总数。
N 叉树输入通过序列遍历进行序列化,每组子节点由空值分隔(参见示例)。
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.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
示例 1:

输入:root = [1,null,3,2,4,null,5,6]
输出:3
示例 2:

输入:root = [1,null,2,3,4,5,null,null,6,7,null,8,null,9,10,null,null,11,null,12,null,13,null,null,14]
输出:5
提示:
- 树的深度不超过 1000 。
- 树的节点数为 [0, 104] 之间。
如果根节点具有 N子节点,然后此 N 子节点对应关系 N 子树。回想起 N 子树最大深度的最大值为 getMaxDepth,则该 NN 叉树的最大深度为 getMaxDepth+1。
每个子树的最大深度可以用相同的方法计算。因此,我们可以使用“深度优先搜索”方法进行计算。 N 叉树的最大深度。具体而言,在计算电流 N 叉树的最大深度,您可以首先递归计算其每个子树的最大厚度,然后在中计算。 O(1) 计算电流的时间 N 叉树的最大深度。访问空节点时递归退出。
var maxDepth = function(root) {
if(!root){return 0}
let getMaxDepth=0
let children=root.children
for(let child of children){
let max=maxDepth(child)
getMaxDepth=Math.max(getMaxDepth,max)
}
return getMaxDepth+1
};
leetcode: https://leetcode-cn.com/problems/maximum-depth-of-n-ary-tree/
版权声明
所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除
itfan123



