zoukankan      html  css  js  c++  java
  • 【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
  • 相关阅读:
    Centos6.7 编译安装 MySQL教程
    python os os.path模块学习笔记
    Ubuntu无线转有线教程
    k8s 部署kube-dns
    k8s-应用快速入门(ma)
    kubectl工具管理应用生命周期
    k8s-部署WEB-UI(dashboard)
    k8s-集群状态及部署一个实例
    k8s-创建node节点kubeconfig配置文件
    k8s-flannel容器集群网络部署
  • 原文地址:https://www.cnblogs.com/seyjs/p/6419102.html
Copyright © 2011-2022 走看看