-
Notifications
You must be signed in to change notification settings - Fork 0
/
find-bottom-left-tree-value.js
58 lines (52 loc) · 1.18 KB
/
find-bottom-left-tree-value.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
52
53
54
55
56
57
/**
* 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)
* }
*/
/**
* 513. 找树左下角的值
* @param {TreeNode} root
* @return {number}
*/
var findBottomLeftValue = function(root) {
// dfs
let result;
let maxDepth = Number.MIN_VALUE;
const dfs = (root, depth) => {
if (root) {
if (!root.left && !root.right) { // leaf node
if (depth > maxDepth) {
// update
maxDepth = depth;
result = root.val;
}
return;
}
dfs(root.left, depth + 1);
dfs(root.right, depth + 1);
}
}
dfs(root, 1);
return result;
// return bfs(root);
};
// 拿到最后一层的最后一个值
function bfs(root) {
const queue = [root];
let result;
while (queue.length) {
let size = queue.length;
for (let i = 0; i < size; i++){
const node = queue.shift();
if (i === 0) {
result = node.val;
}
node.left && queue.push(node.left);
node.right && queue.push(node.right);
}
}
return result;
}