Skip to content

Commit 52335ae

Browse files
authored
Create 0515-find-largest-value-in-each-tree-row.js
1 parent cff997a commit 52335ae

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val, left, right) {
4+
* this.val = (val===undefined ? 0 : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* BFS | Level order traversal
11+
* Time O(n) | Space O(n)
12+
* https://leetcode.com/problems/find-largest-value-in-each-tree-row/
13+
* @param {TreeNode} root
14+
* @return {number[]}
15+
*/
16+
var largestValues = function(root) {
17+
18+
if(!root) return [];
19+
const result = [];
20+
21+
const bfs = (root) => {
22+
const queue = new Queue();
23+
queue.enqueue(root);
24+
25+
while(!queue.isEmpty()) {
26+
let nodesCount = queue.size();
27+
let max = -Infinity;
28+
while(nodesCount) {
29+
const node = queue.dequeue();
30+
max = Math.max(max, node.val);
31+
if(node.left) queue.enqueue(node.left);
32+
if(node.right) queue.enqueue(node.right);
33+
nodesCount--;
34+
}
35+
result.push(max);
36+
}
37+
}
38+
39+
bfs(root);
40+
return result;
41+
};

0 commit comments

Comments
 (0)