【leetcode】559.N叉树的最大深度
![在这里插入图片描述](https://img-blog.csdnimg.cn/7bd3cd5ef8154d7da99e5cd9badf12f4.png#pic_center)
题目
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
N 叉树输入按层序遍历序列化表示,每组子节点由空值分隔(请参见示例)。
示例 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叉树节点的定义
/**
* // Definition for a Node.
* function Node(val,children) {
* this.val = val;
* this.children = children;
* };
*/
对比二叉树,n叉树的孩子节点个数不一致,但是通过children
的就可以遍历每个孩子节点了,所以这道题本质与【leetcode】104.二叉树的最大深度是一样的,思路也完全一样,这里同样给出递归和迭代两种写法。
代码
一、递归法
/**
* // Definition for a Node.
* function Node(val,children) {
* this.val = val;
* this.children = children;
* };
*/
/**
* @param {Node|null} root
* @return {number}
*/
var maxDepth = function(root) {
// 递归返回条件,空节点看作高度为0的树
if(!root) return 0
let max = 0
// 后序遍历,通过children遍历所有孩子节点并计算得到高度
for(let i = 0 ; i < root.children.length ; i++){
const cur = maxDepth(root.children[i])
max = max > cur ? max : cur
}
// 返回最终的高度
return 1 + max
};
二、迭代法(层序遍历)
/**
* // Definition for a Node.
* function Node(val,children) {
* this.val = val;
* this.children = children;
* };
*/
/**
* @param {Node|null} root
* @return {number}
*/
var maxDepth = function(root) {
if(!root) return 0
let queue = [root]
let depth = 0
while(queue.length){
const levelLength = queue.length //每一层的节点个数
for(let i = 0 ; i < levelLength ; i++){
const cur = queue.shift()
// 这里的逻辑和二叉树不同
for(let i = 0 ; i < cur.children.length ; i++){
queue.push(cur.children[i])
}
}
depth++
}
return depth
};
关注我的专栏,每天更新三道leetcode题解,一起变强!