-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path104.二叉树的最大深度.ts
62 lines (60 loc) · 1.26 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
/*
* @lc app=leetcode.cn id=104 lang=typescript
*
* [104] 二叉树的最大深度
*/
// @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)
* }
* }
*/
/**
* BFS 迭代写法
* @param root
* @returns
*/
function maxDepth(root: TreeNode | null): number {
if (root === null) {
return 0
}
let ans = 0
const stk = [root]
while (stk.length > 0) {
let len = stk.length
while (len > 0) {
let temp = stk.shift()
if (temp && temp.left !== null) {
stk.push(temp.left)
}
if (temp && temp.right !== null) {
stk.push(temp.right)
}
len--
}
ans++
}
return ans
};
// @lc code=end
/**
* DFS 递归写法
* @param root
* @returns
*/
function maxDepthDFS(root: TreeNode | null): number {
if (root === null) {
return 0
}
let leftDepth = maxDepth(root.left)
let rightDpth = maxDepth(root.right)
return Math.max(leftDepth, rightDpth) + 1
};