1 /* 2 思路:借助棧來實現 3 樹為空時 返回空 4 樹不為空 將根節點如隊列 5 然后將隊列首元素出隊列 如果該元素有左子節點那么左子節點入隊了 如果該元素有右子節點那么右子節點入隊列 6 最后 進隊列的順序也就是出隊列的順序 7 */ 8 import java.util.ArrayList; 9 import java.util.*; 10 import java.util.Iterator; 11 /** 12 public class TreeNode { 13 int val = 0; 14 TreeNode left = null; 15 TreeNode right = null; 16 17 public TreeNode(int val) { 18 this.val = val; 19 20 } 21 22 } 23 */ 24 public class Solution { 25 public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { 26 Queue <TreeNode>queue=new LinkedList<TreeNode>(); 27 ArrayList <Integer>list=new ArrayList<Integer>(); 28 if(root==null)return list; 29 queue.offer(root); 30 while(!queue.isEmpty()){ 31 TreeNode t=queue.poll(); 32 list.add(t.val); 33 if(t.left!=null){ 34 queue.offer(t.left); 35 } 36 if(t.right!=null){ 37 queue.offer(t.right); 38 } 39 } 40 return list; 41 42 } 43 }