Python solution with detailed explanation


  • 1
    G

    Solution

    Find Largest Value in Each Tree Row https://leetcode.com/problems/find-largest-value-in-each-tree-row/?tab=Description

    Algorithm

    • Do a level order traversal and find the maximum in each row.
    from collections import deque
    class Solution(object):
        def largestValues(self, root):
            """
            :type root: TreeNode
            :rtype: List[int]
            """
            q = deque()
            if root:
                q.append(root)
            result = []
            while len(q):
                result.append(float('-inf'))
                for _ in range(len(q)):
                    top = q.popleft()
                    result[-1] = max(result[-1], top.val)
                    if top.left:
                        q.append(top.left)
                    if top.right:
                        q.append(top.right)
            return result
    

  • 0
    A

    thanks for posting, where is the detailed explanation?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.