from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution1:
def largestValues(self, root: Optional[TreeNode]) -> list[int]:
result, nodes = [], [x for x in [root] if x]
while nodes:
result.append(max(x.val for x in nodes))
_next = []
_next.extend([x.left for x in nodes if x.left])
_next.extend([x.right for x in nodes if x.right])
nodes = _next
return result
class Solution:
# https://leetcode.com/problems/find-largest-value-in-each-tree-row/solutions/99000/python-bfs/
def largestValues(self, root: Optional[TreeNode]) -> list[int]:
result, nodes = [], [root]
while any(nodes):
result.append(max(x.val for x in nodes))
nodes = [x for n in nodes for x in [n.left, n.right] if x]
return result
515. Find Largest Value in Each Tree Row - LeetCode
ยท One min read