//第一種作法 public class Solution {學習
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { ArrayList <Integer> li=new ArrayList<Integer>(); ArrayList <TreeNode> q=new ArrayList<TreeNode>(); if(root==null) return li; q.add(root); while(q.size()!=0){ TreeNode temp = q.remove(0); if(temp.left!=null) q.add(temp.left); if(temp.right!=null) q.add(temp.right); li.add(temp.val); } return li; }
}code
//順帶學習下隊列的用法隊列
public class Solution {rem
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { ArrayList <Integer> li=new ArrayList<Integer>(); Queue <TreeNode> q=new LinkedBlockingQueue<TreeNode>(); if(root==null) return li; q.add(root); while(q.size()!=0){ TreeNode temp = q.poll(); if(temp.left!=null) q.add(temp.left); if(temp.right!=null) q.add(temp.right); li.add(temp.val); } return li; }
}io