function maxDepth(nums) {
let depth = 0;
function dfs(list, depth) {
let max = depth;
for(let item of list) {
if(Array.isArray(item)) {
// 比较同一层级元素间最大深度
max = Math.max(max,dfs(item, depth+1))
}
}
return max
}
depth = dfs(nums,1)
return depth
}
var tests = [1,[2,[3,[4],[5,[6,[7]],[6],[8]],[4],3]],0]
maxDepth(tests)
## bfs实现
function maxDepth(nums) {
let deep = 0;
let temp = [...nums];
while(temp.length) {
let length = temp.length;
deep++
while(length) {
let item = temp.shift();
if(Array.isArray(item)) {
temp.push(...item)
}
length--
}
}
return deep
}
var tests = [1,[2,[3,[4],[5,[6,[7]],[6],[8]],[4],3]],0]
maxDepth(tests)
dfs实现
通过递归的形式向下传递当前层级的深度,比较同一层级所有元素中层级中的最大值并返回
var tests = [1,[2,[3,[4],[5,[6,[7]],[6],[8]],[4],3]],0] maxDepth(tests)
function maxDepth(nums) { let deep = 0; let temp = [...nums];
}
var tests = [1,[2,[3,[4],[5,[6,[7]],[6],[8]],[4],3]],0] maxDepth(tests)