PU Find Largest Value in Each Tree Row

Jan 01, 1970

You need to find the largest value in each row of a binary tree.

Example:

Input: 

          1
         / 
        3   2
       /      
      5   3   9 

Output: [1, 3, 9]

Python Solution:

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
    def largestValues(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        stack = []
        def preorder(root, level):
            if not root: return
            if level == len(stack):
                stack.append(root.val)
            else:
                stack[level] = max(root.val, stack[level])
            preorder(root.left, level + 1)
            preorder(root.right, level + 1)
        preorder(root, 0)
        return stack

Summary:

  • level == len(stack), there are several similar problems.

LeetCode: 515. Find Largest Value in Each Tree Row