-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path104.二叉树的最大深度.js
52 lines (44 loc) · 970 Bytes
/
104.二叉树的最大深度.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
/*
* @lc app=leetcode.cn id=104 lang=javascript
*
* [104] 二叉树的最大深度
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function (root) {
// 方法 1 通过子问题解决
// if (root == null) {
// return 0;
// }
// const leftHeight = maxDepth(root.left)
// const rightHeight = maxDepth(root.right)
// return Math.max(leftHeight, rightHeight) + 1
// 方法 2
let res = 0;
let depth = 0;
const traverse = (root) => {
if (root === null) {
res = Math.max(res, depth);
return;
}
// 前序位置
depth++;
traverse(root.left);
traverse(root.right);
// 后序位置
depth--;
}
traverse(root);
return res;
};
// @lc code=end