找到二叉树每一层最大的数,并输出
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> largestValues(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
if(root ==null){
return result;
}
result.add(root.val);
LinkedList<TreeNode> temp = new LinkedList<TreeNode>();
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
TreeNode current = null;
queue.offer(root);
while(!queue.isEmpty()){
List<Integer> needSort = new ArrayList<Integer>();
int size = queue.size();
for(int i=0;i<size;i++){
current = queue.poll();
System.out.println(current.val);
if(current.left!=null){
temp.offer(current.left);
needSort.add(current.left.val);
}
if(current.right!=null){
temp.offer(current.right);
needSort.add(current.right.val);
}
}
if(!needSort.isEmpty()){
Collections.sort(needSort);
result.add(needSort.get(needSort.size()-1));
}
if(!temp.isEmpty()){
int siz = temp.size();
for(int j=0;j<siz;j++){
queue.offer(temp.poll());
}
}
}
return result;
}
}
层次遍历时,queue pop出当层所有节点后,再加入下一层节点。
网友评论