题目链接
层序遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> list = new ArrayList();
Deque<TreeNode> queue = new LinkedList<TreeNode>();
if(root != null){
queue.offer(root);
}
while(!queue.isEmpty()){
int size = queue.size();
// Java最小值整型常量表示方法
int max = Integer.MIN_VALUE;
for(int i = 0; i < size; i++){
TreeNode node = queue.poll();
if(node.val > max){
max = node.val;
}
if(node.left != null){
queue.offer(node.left);
}
if(node.right != null){
queue.offer(node.right);
}
}
list.add(max);
}
return list;
}
}