1,问题简述
您需要在二叉树的每一行中找到最大的值。
2,示例
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: [1, 3, 9]
3,题解思路
队列的使用
4,题解程序
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class LargestValuesTest {
public static void main(String[] args) {
TreeNode t1 = new TreeNode(1);
TreeNode t2 = new TreeNode(3);
TreeNode t3 = new TreeNode(2);
TreeNode t4 = new TreeNode(5);
TreeNode t5 = new TreeNode(3);
TreeNode t6 = new TreeNode(9);
t1.left = t2;
t1.right = t3;
t2.left = t4;
t2.right = t5;
t3.right = t6;
List<Integer> integerList = largestValues(t1);
System.out.println("integerList = " + integerList);
}
public static List<Integer> largestValues(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()) {
int size = queue.size();
int currentLevelMaxValue = Integer.MIN_VALUE;
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
currentLevelMaxValue = Math.max(currentLevelMaxValue, node.val);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
list.add(currentLevelMaxValue);
}
return list;
}
}
5,题解程序图片版
6,总结
队列的使用,队列的特点是先进先出,这也是日常生活很常见的一种的场景,购物,进站等场景吧,计算机里面队列的使用也是很常见的,比如打开计算机时,机器是如何运转的,优先级队列的运用却大有其奥妙之处,这就是队列的场景
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有