// Title description // Print out each node of the binary tree from top to bottom, and the nodes at the same level are printed from left to right. 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) { // You can return an empty ArrayList, you can't go back to null, try to avoid returning null, it is easy to cause exceptions 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; }