从上往下打印出二叉树的每个节点,同层节点从左至右打印。
这个题目考查的就是单纯的广度优先遍历。
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> res = new ArrayList<Integer>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
TreeNode temp;
if( root == null) return res;
queue.add(root);
while(!queue.isEmpty()){
int size = queue.size();
for(int i=0; i<size; i++){
temp = queue.poll();
res.add(temp.val);
if(temp.left != null) queue.add(temp.left);
if(temp.right != null) queue.add(temp.right);
}
}
return res;
}
}