题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
import java.util.LinkedList;
import java.util.Queue;
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> arr=new ArrayList<Integer>();
if(root==null)
return arr;
Queue<TreeNode> queue=new LinkedList<TreeNode>();
queue.offer(root);
while(queue.peek()!=null){
TreeNode temp=queue.poll();
arr.add(temp.val);
if(temp.left!=null)
queue.offer(temp.left);
if(temp.right!=null)
queue.offer(temp.right);
}
return arr;
}
}