Skip to content

Commit df6d389

Browse files
committed
[LeetCode Sync] Runtime - 5 ms (9.78%), Memory - 19.8 MB (6.38%)
1 parent 93dee3b commit df6d389

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
<p>Given the <code>root</code> of a binary tree, return <em>an array of the largest value in each row</em> of the tree <strong>(0-indexed)</strong>.</p>
2+
3+
<p>&nbsp;</p>
4+
<p><strong class="example">Example 1:</strong></p>
5+
<img alt="" src="https://assets.leetcode.com/uploads/2020/08/21/largest_e1.jpg" style="width: 300px; height: 172px;" />
6+
<pre>
7+
<strong>Input:</strong> root = [1,3,2,5,3,null,9]
8+
<strong>Output:</strong> [1,3,9]
9+
</pre>
10+
11+
<p><strong class="example">Example 2:</strong></p>
12+
13+
<pre>
14+
<strong>Input:</strong> root = [1,2,3]
15+
<strong>Output:</strong> [1,3]
16+
</pre>
17+
18+
<p>&nbsp;</p>
19+
<p><strong>Constraints:</strong></p>
20+
21+
<ul>
22+
<li>The number of nodes in the tree will be in the range <code>[0, 10<sup>4</sup>]</code>.</li>
23+
<li><code>-2<sup>31</sup> &lt;= Node.val &lt;= 2<sup>31</sup> - 1</code></li>
24+
</ul>
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def largestValues(self, root: Optional[TreeNode]) -> List[int]:
9+
if not root:
10+
return []
11+
12+
res = []
13+
q = deque([root])
14+
15+
#BFS
16+
while q:
17+
m = float("-inf")
18+
19+
for _ in range(len(q)):
20+
node = q.popleft()
21+
m = max(m, node.val)
22+
23+
if (node.left):
24+
q.append(node.left)
25+
if (node.right):
26+
q.append(node.right)
27+
res.append(m)
28+
29+
return res

0 commit comments

Comments
 (0)