Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 9158beb

Browse files
committedMar 4, 2025
Add solution #515
1 parent 19819aa commit 9158beb

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
 

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,7 @@
411411
509|[Fibonacci Number](./0509-fibonacci-number.js)|Easy|
412412
513|[Find Bottom Left Tree Value](./0513-find-bottom-left-tree-value.js)|Medium|
413413
514|[Freedom Trail](./0514-freedom-trail.js)|Hard|
414+
515|[Find Largest Value in Each Tree Row](./0515-find-largest-value-in-each-tree-row.js)|Medium|
414415
520|[Detect Capital](./0520-detect-capital.js)|Easy|
415416
521|[Longest Uncommon Subsequence I](./0521-longest-uncommon-subsequence-i.js)|Easy|
416417
530|[Minimum Absolute Difference in BST](./0530-minimum-absolute-difference-in-bst.js)|Easy|
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* 515. Find Largest Value in Each Tree Row
3+
* https://leetcode.com/problems/find-largest-value-in-each-tree-row/
4+
* Difficulty: Medium
5+
*
6+
* Given the root of a binary tree, return an array of the largest value in each row
7+
* of the tree (0-indexed).
8+
*/
9+
10+
/**
11+
* Definition for a binary tree node.
12+
* function TreeNode(val, left, right) {
13+
* this.val = (val===undefined ? 0 : val)
14+
* this.left = (left===undefined ? null : left)
15+
* this.right = (right===undefined ? null : right)
16+
* }
17+
*/
18+
/**
19+
* @param {TreeNode} root
20+
* @return {number[]}
21+
*/
22+
var largestValues = function(root) {
23+
if (!root) return [];
24+
const result = [];
25+
const queue = [root];
26+
27+
while (queue.length) {
28+
const level = queue.length;
29+
let max = -Infinity;
30+
for (let i = 0; i < level; i++) {
31+
const node = queue.shift();
32+
max = Math.max(max, node.val);
33+
if (node.left) queue.push(node.left);
34+
if (node.right) queue.push(node.right);
35+
}
36+
result.push(max);
37+
}
38+
39+
return result;
40+
};

0 commit comments

Comments
 (0)
Please sign in to comment.