【leetcode】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]

题目要求计算二叉树每一层的最大值,并且将最大值组成一个列表输出。从题目要求很容易可以看出,这是一个二叉树的层序遍历,在遍历的过程中对比求出每一层的最大值。层序遍历的思路就是从根节点开始,依次把每个节点的左右节点放入一个队列中,接着依次遍历队列中的所有节点。

# 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]
        """
        res = []
        if root == None:
            return res
        queue = []
        root.index = 0  #修改TreeNode定义,加入index成员,表示该节点所在的层数
        res.append(root.val)
        p = root
        while p!= None:
            #print p.val
            if p.left != None:
                p.left.index = p.index + 1
                queue.append(p.left)
            if p.right != None:
                p.right.index = p.index + 1
                queue.append(p.right)
            if len(res) <= p.index:
                res.append(p.val)
            else:
                res[p.index] = max(res[p.index],p.val)   #比较每层的最大值
            if len(queue) == 0:
                break
            p = queue[0]
            del queue[0]
        return res
原文地址:https://www.cnblogs.com/seyjs/p/6419102.html