/**
* 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) {
//为了避免队列中的节点混淆,分别使用两个计数器来记录当前队列中当前层节点的个数和下一层节点的个数
int current = 0;
int next = 0;
Queue<TreeNode> queue = new LinkedList<>();
int max = Integer.MIN_VALUE;
if(root != null){
queue.offer(root);
current = 1;
}
//使用动态数组来存储结果
ArrayList<Integer> result = new ArrayList<>();
//层次遍历二叉树
while(!queue.isEmpty()){
//遍历每一层的节点遍历时需要减去当前成的计数器,计入子节点时需要加上下一层节点的个数
TreeNode node = queue.poll();
if(max < node.val){
max = node.val;
}
current--;
if(node.left != null){
queue.offer(node.left);
next++;
}
if(node.right != null){
queue.offer(node.right);
next++;
}
//m当每层遍历结束时需要对计数器和结果重新处理
if(current == 0){
current = next;
next = 0;
result.add(max);
max = Integer.MIN_VALUE;
}
}
return result;
}
}
二叉树每层的最大值java实现
最新推荐文章于 2022-05-24 10:39:25 发布