题目
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]
讲解
又是树的层次遍历题。相同的题我已经做了两个了:637. Average of Levels in Binary Tree、429. N-ary Tree Level Order Traversal
Java代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
List<Integer> result = new ArrayList<>();
public List<Integer> largestValues(TreeNode root) {
if(root==null){
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
int count = 1;
while(!queue.isEmpty()){
List<Integer> list = new ArrayList<>();
int floorSize = 0;
for(int i=0;i<count;i++){
TreeNode now = queue.poll();
list.add(now.val);
if(now.left!=null){
queue.offer(now.left);
floorSize++;
}
if(now.right!=null){
queue.offer(now.right);
floorSize++;
}
}
int max = list.get(0);
for(Integer x:list){
if(max<x){
max = x;
}
}
count = floorSize;
result.add(max);
}
return result;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。