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;
}
}