Leetcode515. Find Largest Value in Each Tree Row

本文介绍了一种寻找二叉树每一层中最大值的方法,通过广度优先搜索实现,仅需一次遍历即可得到所有层级的最大值。

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

515. Find Largest Value in Each Tree Row

1、原题

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]

2、题意与思路

这道题的意思很简单,就是寻找一个二叉树中每一层中最大的值。
这道题的思路也是很简单,就是一个简单的广搜问题。但是这里有点不同的是,我们要找到同一层中的数值。一开始我的想法是还要用一个新的队列来记录每一个元素的层数。但是这样做后,感觉效果很不好。后来想到了我们可以直接根据我们队列的size大小来记录每一层的宽度,这样就简单了很多。

3、代码

public List<Integer> largestValues(TreeNode root) {
		 //记录每一层的最大值
		 List<Integer> list = new ArrayList<Integer>();
		 //用于广搜记录
		 List<TreeNode> queue = new ArrayList<TreeNode>();
		 
		 int queueSize = root == null ? 0 : 1;
		 queue.add(root);
		 while (queueSize > 0) {
			 int maxValue = Integer.MIN_VALUE;
			 //收搜每一层
			 for (int i = 0; i < queueSize; i++) {
				 TreeNode item = queue.remove(0);
				 maxValue = maxValue > item.val ? maxValue : item.val;
				 if (item.left != null) queue.add(item.left);
				 if (item.right != null) queue.add(item.right);
			 }
			 list.add(maxValue);
			 //获取下一层的size
			 queueSize = queue.size();
		 }
		 
		 return list;
	 }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值