给定一棵二叉树的根节点root,请找出该二叉树中每一层的最大值。
思路找到每一层的最大值,立即想到BFS
代码
class Solution {
public List largestValues(TreeNode root) {
if (root == null) {
return new ArrayList();
}
List res = new ArrayList();
Queue queue = new ArrayDeque();
queue.offer(root); // offer方法,入队
while (!queue.isEmpty()) { // isEmpty方法,判断队空
int len = queue.size(); // size方法,队列长度
int maxVal = Integer.MIN_VALUE; // MIN_VALUE
while (len > 0) {
len--;
TreeNode t = queue.poll(); // poll方法,出队
maxVal = Math.max(maxVal, t.val); // Math.max方法
if (t.left != null) {
queue.offer(t.left);
}
if (t.right != null) {
queue.offer(t.right);
}
}
res.add(maxVal); // add方法
}
return res;
}
}



