// 题目描述
// 从上往下打印出二叉树的每个节点,同层节点从左至右打印。
public static class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
public static ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
// 可以返回个空ArrayList 不能反悔null ,尽量避免返回null 容易引起异常
ArrayList<Integer> arrayList = new ArrayList<Integer>();
Queue<TreeNode> stack0 = new LinkedList<TreeNode>();
Queue<TreeNode> stack1 = new LinkedList<TreeNode>();
if (root != null) {
stack0.offer(root);
}
while (!stack0.isEmpty() || !stack1.isEmpty()) {
while (!stack0.isEmpty()) {
TreeNode current = stack0.poll();
arrayList.add(current.val);
if (current.left != null) {
stack1.offer(current.left);
}
if (current.right != null) {
stack1.offer(current.right);
}
}
while (!stack1.isEmpty()) {
TreeNode current = stack1.poll();
arrayList.add(current.val);
if (current.left != null) {
stack0.offer(current.left);
}
if (current.right != null) {
stack0.offer(current.right);
}
}
}
return arrayList;
}