-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximum-depth-of-binary-tree.js
More file actions
47 lines (41 loc) · 1.06 KB
/
maximum-depth-of-binary-tree.js
File metadata and controls
47 lines (41 loc) · 1.06 KB
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
/**
* 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)
* }
*/
/**
* 二叉树的最大深度
* 参考: https://www.bilibili.com/video/BV1Kb41127fT?p=40 (【浙江大学】数据结构)
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function (root) {
// 1. 递归
if (!root) return 0;
const leftHeihgt = maxDepth(root.left);
const rightHeight = maxDepth(root.right);
const maxHeight = Math.max(leftHeihgt, rightHeight);
return maxHeight + 1;
// 2. BFS
// return levelOrder(root);
};
// 层序遍历获取最大深度
function levelOrder(root) {
if (!root) return 0;
let depth = 0;
const queue = [];
queue.push(root);
while (queue.length) {
let size = queue.length;
depth++;
while (size--) {
const node = queue.shift();
node.left && queue.push(node.left);
node.right && queue.push(node.right);
}
}
return depth;
}