[LeetCode]Find Largest Element in Each Row

题目描述:

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

 

本文链接:http://bookshadow.com/weblog/2017/02/12/leetcode-find-largest-element-in-each-row/
请尊重作者的劳动成果,转载请注明出处!书影博客保留对文章的所有权利。

如果您喜欢这篇博文,欢迎您捐赠书影博客: ,查看支付宝二维码

Pingbacks已关闭。

暂无评论

张贴您的评论