剑指Offer:从上往下打印二叉树(JAVA实现)
作者:互联网
2021.2.13
考点:
树、队列
思路:
- 巧妙运用队列这个优秀的数据结构
- 注意NULL的情况
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> ans = new ArrayList<>();
if(root == null){
return ans;
}
ArrayDeque<TreeNode> queue = new ArrayDeque<>();
queue.offer(root);
int count = 1;
while(queue.size() != 0){
int temp = 0;
for(int i = 0; i< count;i++){
TreeNode tempNode = queue.poll();
ans.add(tempNode.val);
if(tempNode.left != null){
queue.offer(tempNode.left);
temp++;
}
if(tempNode.right != null){
queue.offer(tempNode.right);
temp++;
}
}
}
return ans;
}
}
标签:JAVA,Offer,int,offer,tempNode,queue,二叉树,ans,null 来源: https://blog.csdn.net/qq_26558047/article/details/113802847