Skip to content

Latest commit

 

History

History
62 lines (52 loc) · 1.06 KB

515.md

File metadata and controls

62 lines (52 loc) · 1.06 KB
  1. Find Largest Value in Each Tree Row
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]

my thoughts:

1. peel, peel, peel the onion.

my solution:

**********68ms
# 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]
        """
        if not root:
            return []
        res = [root.val]
        cur = [root]
        while cur:
            prev = cur
            cur = []
            for n in prev:
                if n.left:
                    cur.append(n.left)
                if n.right:
                    cur.append(n.right)
            if cur:
                res.append(max(n.val for n in cur))
        return res

my comments:


from other ppl's solution:

1. N/A