Quantcast
Channel: 书影 - Entries for the tag leetcode
Viewing all articles
Browse latest Browse all 559

[LeetCode]Find Largest Element in Each Row

$
0
0

题目描述:

LeetCode 515. Find Largest Element in Each 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]

题目大意:

给定二叉树,返回其每一行的最大元素。

解题思路:

二叉树的层次遍历

Python代码:

# 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 findValueMostElement(self, root):
        """
        :type root: TreeNode
        :rtype: List[int]
        """
        if not root: return []
        qa, ans = [root], []
        while qa:
            maxn = None
            qb = []
            for n in qa:
                maxn = max(n.val, maxn)
                if n.left: qb.append(n.left)
                if n.right: qb.append(n.right)
            ans.append(maxn)
            qa = qb
        return ans

 


Viewing all articles
Browse latest Browse all 559

Trending Articles