import java.util.ArrayList; import java.util.Queue; import java.util.LinkedList; /** 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> list = new ArrayList<>(); if (null == root) { return list; } Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); while (queue.size() != 0) { TreeNode tmp = queue.poll(); list.add(tmp.val); if (null != tmp.left) { queue.add(tmp.left); } if (null != tmp.right) { queue.add(tmp.right); } } return list; } }
Queue队列的用法详见:https://www.runoob.com/java/data-queue.html