从上往下打印出二叉树的每个节点,同层节点从左至右打印。
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 result=new ArrayList();
if(root==null)
{
return result;
}
TreeNode p=root;
Queue qt=new LinkedList();
qt.offer(p);
while(qt.size()!=0)
{
TreeNode tn=(TreeNode)qt.poll();
result.add(tn.val);
if(tn.left!=null)
qt.offer(tn.left);
if(tn.right!=null)
qt.offer(tn.right);
}
return result;
}
}
Queue qt=new LinkedList();