leetcode讲解–515. Find Largest Value in Each Tree Row

51次阅读

共计 856 个字符,预计需要花费 3 分钟才能阅读完成。

题目
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;
}
}

正文完
 0