LeetCode.515 Find Largest Value in Each Tree Row

本文介绍了一种算法,该算法通过层序遍历二叉树并找出每一层的最大值。采用两个队列交替使用的方式实现遍历,确保了遍历过程中能够正确地区分不同的层级。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<Integer> largestValues(TreeNode root) {
        //给定二叉树,找出每层最大的数据
        //思路:层序遍历整个树,然后从每层中找出最大的数
        List<Integer> list=new ArrayList<>();
        if(root==null) return list;
        
        Queue<TreeNode> oddQu=new LinkedList<>();
        Queue<TreeNode> evenQu=new LinkedList<>();
        oddQu.add(root);
        int count=1;
        while(!oddQu.isEmpty()||!evenQu.isEmpty()){
            int cur=Integer.MIN_VALUE;
            while(count%2==1&&!oddQu.isEmpty()){
                TreeNode temp=oddQu.poll();
                cur=Math.max(temp.val,cur);
                if(temp.left!=null){
                    evenQu.add(temp.left);
                }
                if(temp.right!=null){
                    evenQu.add(temp.right);
                }
            }
            //偶数层
            while(count%2==0&&!evenQu.isEmpty()){
                TreeNode temp=evenQu.poll();
                cur=Math.max(temp.val,cur);
                if(temp.left!=null){
                    oddQu.add(temp.left);
                }
                if(temp.right!=null){
                    oddQu.add(temp.right);
                }
            }
            count++;
            list.add(cur);
        }
        return list;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值