515. Find Largest Value in Each Tree Row
来源:互联网 发布:java杨辉三角四行 编辑:程序博客网 时间:2024/05/18 02:07
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]
题意:找出二叉树中,每层节点中的最大值。
解题思路:
BFS(广度优先搜索),可以看做是层序遍历的扩展。由于层序遍历时,队列里并不能确定每层节点数,因此,只需要在层序遍历的过程中,引入一个值(queueSize)来标识每层节点数,然后利用for循环筛选出每层节点里的最大值即可。
public List<Integer> largestValues(TreeNode root) { List<Integer> result = new ArrayList<Integer>(); if(root==null) return result; if(root.left==null&&root.right==null) { result.add(root.val); return result; } //在常规层序遍历中,队列里并不能反映出每层节点数, //因此需要一个queueSize变量来记录每层一共有几个节点 int queueSize = root == null? 0:1; Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.offer(root); while(!queue.isEmpty()){ int largestNode = Integer.MIN_VALUE; for (int i = 0; i < queueSize; i++) { TreeNode node = queue.poll(); largestNode = Math.max(largestNode, node.val); if(node.left != null){ queue.offer(node.left); } if(node.right != null){ queue.offer(node.right); } } queueSize = queue.size(); result.add(largestNode); } return result; }
阅读全文
0 0
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- LeetCode 515. Find Largest Value in Each Tree Row
- 515. Find Largest Value in Each Tree Row
- LeetCode OJ 515. Find Largest Value in Each Tree Row
- 515. Find Largest Value in Each Tree Row
- 515. Find Largest Value in Each Tree Row
- week3-NO.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
- OAuth2.0
- java 中三种常见内存溢出错误的处理方法
- jeestite第一天--环境准备
- boost 1.48 vs2008编译
- CentOS 6.9 安装IPtux局域网聊天工具
- 515. Find Largest Value in Each Tree Row
- Drupal8 PHPExcel_Shared_Date not found
- 配置tomcat文件服务器
- 包含min函数的栈
- 【剑指offer之二进制中1的个数】
- 我的机器学习之路-Regression(二)
- spring中scope(作用越)理解
- mysql主从复制(四)
- 搭建JEESZ分布式架构9--消息中间件简介