Leetcode 515 Solution
This article provides solution to leetcode question 515 (find-largest-value-in-each-tree-row)
Access this page by simply typing in "lcs 515" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/find-largest-value-in-each-tree-row
Solution
# 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 Solution:
def largestValues(self, root: Optional[TreeNode]) -> List[int]:
q = collections.deque()
if root:
q.append(root)
ans = []
while q:
s = len(q)
max_val = -sys.maxsize
for _ in range(s):
node = q.popleft()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
max_val = max(max_val, node.val)
ans.append(max_val)
return ans