-
Notifications
You must be signed in to change notification settings - Fork 1
/
104.ts
115 lines (110 loc) · 2.44 KB
/
104.ts
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/*
* @lc app=leetcode.cn id=104 lang=typescript
*
* [104] 二叉树的最大深度
*
* https://leetcode.cn/problems/maximum-depth-of-binary-tree/description/
*
* algorithms
* Easy (77.91%)
* Likes: 1870
* Dislikes: 0
* Total Accepted: 1.4M
* Total Submissions: 1.8M
* Testcase Example: '[3,9,20,null,null,15,7]'
*
* 给定一个二叉树 root ,返回其最大深度。
*
* 二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。
*
*
*
* 示例 1:
*
*
*
*
*
*
* 输入:root = [3,9,20,null,null,15,7]
* 输出:3
*
*
* 示例 2:
*
*
* 输入:root = [1,null,2]
* 输出:2
*
*
*
*
* 提示:
*
*
* 树中节点的数量在 [0, 10^4] 区间内。
* -100 <= Node.val <= 100
*
*
*/
class TreeNode {
val: number
left: TreeNode | null
right: TreeNode | null
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = (val === undefined ? 0 : val)
this.left = (left === undefined ? null : left)
this.right = (right === undefined ? null : right)
}
}
// @lc code=start
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
// 解法1
// function maxDepth(root: TreeNode | null): number {
// if(!root) return 0
// function travel(node: TreeNode, curDepth){
// if(!node.left && !node.right){
// return curDepth
// }
// if(node.left && node.right){
// return curDepth + Math.max(travel(node.left, curDepth ), travel(node.right, curDepth))
// }
// if(node.left){
// return curDepth + travel(node.left, curDepth)
// }
// if(node.right){
// return curDepth + travel(node.right, curDepth)
// }
// }
// return travel(root, 1)
// };
// 解法2: 2024.09.12
function maxDepth(root: TreeNode | null): number {
let maxDep = 0
let curDep = 0
function travel(root){
if(root === null){
maxDep = Math.max(curDep, maxDep)
return
}
curDep++
travel(root.left)
travel(root.right)
curDep--
}
travel(root)
return maxDep
};
// @lc code=end