-
Notifications
You must be signed in to change notification settings - Fork 0
/
559.n-叉树的最大深度.js
55 lines (50 loc) · 1.07 KB
/
559.n-叉树的最大深度.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
* @lc app=leetcode.cn id=559 lang=javascript
*
* [559] N 叉树的最大深度
*/
// @lc code=start
/**
* // Definition for a Node.
* function Node(val,children) {
* this.val = val;
* this.children = children;
* };
*/
/**
* @param {Node|null} root
* @return {number}
*/
// recursive method
// var maxDepth = function(root) {
// if (!root) {
// return 0
// }
// let subTreeDepth = 0
// for (let index = 0; index < root.children.length; index++) {
// const subTree = root.children[index]
// subTreeDepth = Math.max(subTreeDepth, maxDepth(subTree))
// }
// return subTreeDepth + 1
// }
// iteractive method
var maxDepth = function(root) {
let maxDepth = 0
let curDepth = 0
traverse(root)
return maxDepth
function traverse(root) {
if (!root) {
return
}
curDepth++
maxDepth = Math.max(maxDepth, curDepth) // key step
for (let index = 0; index < root.children.length; index++) {
const child = root.children[index]
traverse(child)
}
curDepth--
}
}
// @lc code=end
module.exports = { maxDepth }