从上往下打印出二叉树的每个节点,同层节点从左至右打印。
题解:
二叉树广度优先遍历
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> result = new ArrayList<Integer>();
Queue<TreeNode> queue = new LinkedList<TreeNode>();
if(root == null) return result;
queue.offer(root);
while(!queue.isEmpty()){
TreeNode temp = queue.poll();
result.add(temp.val);
if(temp.left != null){
queue.offer(temp.left);
}
if(temp.right != null){
queue.offer(temp.right);
}
}
return result;
}
}