leetcode 算法题559 (简单142) N叉树的最大深度
- 题目介绍
给定一个 N 叉树,找到其最大深度。
最大深度是指从根节点到最远叶子节点的最长路径上的节点总数。
例如,给定一个 3叉树 :
我们应返回其最大深度,3。
- 说明
树的深度不会超过 1000。
树的节点总不会超过 5000。
- 解法一
/**
* // Definition for a Node.
* function Node(val,children) {
* this.val = val;
* this.children = children;
* };
*/
/**
* @param {Node} root
* @return {number}
*/
var maxDepth = function(root) {
if(!root) {
return 0;
}
if(root.children && root.children.length) {
return Math.max(...root.children.map(child => maxDepth(child))) + 1;
}
return 1;
};
执行用时 : 680 ms, 在所有 JavaScript 提交中击败了97.86%的用户
内存消耗 : 77.1 MB, 在所有 JavaScript 提交中击败了80.82%的用户
- 解法二
/**
* // Definition for a Node.
* function Node(val,children) {
* this.val = val;
* this.children = children;
* };
*/
/**
* @param {Node} root
* @return {number}
*/
var maxDepth = function(root) {
if(!root) {
return 0;
}
let count = 0, temp = [root];
while(temp.length) {
let i = 0, tArray = [];
while(i < temp.length) {
tArray.push(...temp[i++].children);
}
count++;
temp = tArray;
}
return count;
};
执行用时 : 668 ms, 在所有 JavaScript 提交中击败了98.40%的用户
内存消耗 : 77.5 MB, 在所有 JavaScript 提交中击败了71.23%的用户