从上往下打印出二叉树的每个节点,同层节点从左至右打印。
import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; /** public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ 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 treeNode = queue.poll(); if (treeNode.left != null) { queue.offer(treeNode.left); } if (treeNode.right != null) { queue.offer(treeNode.right); } result.add(treeNode.val); } return result; } }