leetcode 515. Find Largest Value in Each Tree Row
来源:互联网 发布:零售软件是什么 编辑:程序博客网 时间:2024/04/30 09:06
515. 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]
解法
层次遍历,每一层入队列,再根据该层的长度分别出队列,再添加出队列的元素对应的左右孩子。直到队列的长度为0。在每一层的操作中,计算最大的元素添加到list中。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public List<Integer> largestValues(TreeNode root) { List<Integer> ret = new ArrayList<Integer>(); if (root == null) { return ret; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while (!queue.isEmpty()) { int max = Integer.MIN_VALUE; int size = queue.size(); for (int i = 0; i < size; i++) { TreeNode head = queue.poll(); if (head.val > max) { max = head.val; } if (head.left != null) { queue.offer(head.left); } if (head.right != null) { queue.offer(head.right); } } ret.add(max); } return ret; }}
阅读全文
1 0
- LeetCode 515. Find Largest Value in Each Tree Row
- LeetCode OJ 515. Find Largest Value in Each Tree Row
- LeetCode笔记:515. Find Largest Value in Each Tree Row
- [leetcode] 515. Find Largest Value in Each Tree Row
- 【LeetCode】515. Find Largest Value in Each Tree Row
- LeetCode;515. Find Largest Value in Each Tree Row
- leetcode 515. Find Largest Value in Each Tree Row
- leetcode 515. Find Largest Value in Each Tree Row
- leetcode-515. Find Largest Value in Each Tree Row
- leetcode 515. Find Largest Value in Each Tree Row
- leetcode 515. Find Largest Value in Each Tree Row
- leetcode 515. Find Largest Value in Each Tree Row
- LeetCode 515. Find Largest Value in Each Tree Row (C++)
- leetcode 515. Find Largest Value in Each Tree Row
- LeetCode#515. Find Largest Value in Each Tree Row
- leetcode 515. Find Largest Value in Each Tree Row
- LeetCode 515. Find Largest Value in Each Tree Row
- [LeetCode] 515. Find Largest Value in Each Tree Row
- 最大生成树+链剖——Luogu1967 [NOIP2013]货车运输
- 生产者与消费者模型
- 使用Eclipse Babel语言包汉化eclipse
- 操作系统(Operating System)16 分布式处理,客户-服务器和集群
- css默认样式
- leetcode 515. Find Largest Value in Each Tree Row
- 支持向量机(SVM)常考点
- JSP用到一个下拉框<select> 页面刷新后,保持选中的值
- HTML5的input
- Google、IBM和Lyft开源的微服务管理框架Istio安装文档
- Python适配器模式
- 传统IO与NIO的比较
- 拷贝文件夹到一个新的文件
- Android Studio新功能解析,你真的了解Instant Run吗?