DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

Find Largest Value in Each Tree Row

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

Example 1:

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

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]:
        mvals = {}
        nodes = [(root, 0)]
        mlevel = -1
        while len(nodes) > 0:
            curr, l = nodes.pop()
            if curr:
                mlevel = max(mlevel, l)
                mvals[l] = max(mvals.get(l, float('-inf')), curr.val)
                nodes.append((curr.left, l + 1))
                nodes.append((curr.right, l + 1))
        return [mvals[l] for l in range(mlevel + 1)]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)