leecode 515. 在每个树行中找最大值

  1. 题目链接 https://leetcode-cn.com/problems/find-largest-value-in-each-tree-row/comments/

  2. 题目描述

    1. 您需要在二叉树的每一行中找到最大的值。
    2. 输入: 
      
                1
               / \
              3   2
             / \   \  
            5   3   9 
      
      输出: [1, 3, 9]
  3. 解题思路

    1. 通过二叉树的层次遍历求每一层的最大值,用队列实现即可。
    • 需要注意的一点是如何当前遍历的元素是第几层,这里有三种方法, 设置哨兵、将节点加入队列的同时将节点的层次信息加入、确定每一层的长度并根据长度对每层循环
  4. 代码

    • python(哨兵)
      from collections import deque
      class Solution:
          def largestValues(self, root: TreeNode) -> List[int]:
              if not root: return []
              
              last, curLast = root, None
              res, index = [root.val], 0
              q = deque([root])
              while q:
                  tmp = q.popleft()    
                  res[index] = max(tmp.val, res[index])
                  
                  if tmp.left:
                      q.append(tmp.left)
                  if tmp.right:
                      q.append(tmp.right)
                  
                  curLast = tmp.right or tmp.left or curLast
                  
                  if tmp == last:
                      index += 1
                      if q:
                          res.append(curLast.val)
                      last = curLast
              return res
                  

       

    • python(每层循环 这是在讨论区转的,然后进行稍加修改)
          def largestValues(self, root):
              """
              :type root: TreeNode
              :rtype: List[int]
              """
              res=[]
              if root==None:
                  return res
              l=[]
              l.append(root)
              while len(l)>0:
                  _max=l[0].val
                  for i in range(0,len(l)):
                      temp_node=l[0]
                      del l[0]
      ,              _max = max(temp_node.val,_max)
       
                      if temp_node.left:
                          l.append(temp_node.left)
                      if temp_node.right:
                          l.append(temp_node.right)
                  res.append(max)
              return res

       

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值