<>题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
<>解题
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(root==null) return list; Queue<TreeNode>
queue= new LinkedList<>(); queue.offer(root); //队列一直不为空的时候执行 while (!queue.
isEmpty()){ //取出来队列先入队列的顶的元素 list.add(queue.peek().val); //取出队列顶元素 TreeNode poll
= queue.poll(); // if(poll.left!=null) queue.offer(poll.left); if(poll.right!=
null) queue.offer(poll.right); } return list; } }