从上往下打印二叉树
题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
代码
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
import java.util.ArrayList;
import java.util.Queue;
import java.util.LinkedList;
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> list= new ArrayList<Integer>();
Queue<TreeNode> queue=new LinkedList<TreeNode>();
queue.offer(root);
TreeNode temp=null;
while((temp=queue.poll())!=null)
{
list.add(temp.val);
TreeNode left=temp.left;
TreeNode right=temp.right;
if(left!=null) queue.offer(left);
if(right!=null) queue.offer(right);
}
return list;
}
}