[Solved] Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).

Table of Contents

Question

Given the root of a binary tree, return an array of the largest value in each row of the tree (0-indexed).

Example 1:

largest e1
Input: root = [1,3,2,5,3,null,9]
Output: [1,3,9]

Example 2:

Input: root = [1,2,3]
Output: [1,3]

Constraints:

  • The number of nodes in the tree will be in the range [0, 104].
  • -231 <= Node.val <= 231 - 1

Python 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: TreeNode) -> List[int]:
        if root==None:
            return
        q=[]
        ans = []
        q.append(root)
        
        while len(q)!=0:
            row = []
            temp = []
            while len(q)!=0:
                row.append(q[0].val)
                if q[0].left:temp.append(q[0].left)
                if q[0].right:temp.append(q[0].right)
                q.pop(0)
            q = temp
            ans.append(max(row))
        
        return ans

Leave a Reply

Your email address will not be published. Required fields are marked *