-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path104.二叉树的最大深度.js
48 lines (47 loc) · 1.08 KB
/
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
/*
* @lc app=leetcode.cn id=104 lang=javascript
*
* [104] 二叉树的最大深度
*/
// @lc code=start
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* DFS
* @param {TreeNode} root
* @return {number}
*/
// var maxDepth = function (root) {
// if (!root) return 0;
// if (!root.left && !root.right) return 1;
// return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
// };
/**
* BFS
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function (root) {
if (!root) return 0;
if (!root.right && !root.left) return 1;
let cur = root;
const que = [root, null];
let level = 1;
while ((cur = que.shift()) !== undefined) {
if (cur === null) {
if (que.length === 0) return level;
level++;
que.push(null);
continue;
}
cur.left && que.push(cur.left);
cur.right && que.push(cur.right);
}
};
// @lc code=end