题目:从上往下打印二叉树的每个结点,同一层的结点按照从左到右的顺序打印
分析:即树的层次遍历,广度优先遍历,借助一个队列来实现,规律是,每次打印一个结点的时候,如果该结点有子节点,则把该结点的子节点放到一个队列的末尾,接下来到队列的头部取出最早进入队列的结点,重复前面的操作直至队列中多有的结点都被打印出来
import java.util.*; public class wr23fromTopToBottom { public static ArrayList<Integer> printFromTopToButtom(TreeNode root){ ArrayList<Integer> list=new ArrayList<>(); Queue<TreeNode> queue=new LinkedList<>(); if(root==null){ return list; } queue.add(root); while(!queue.isEmpty()){ TreeNode temp=queue.poll(); if(temp.left!=null){ queue.add(temp.left); } if(temp.right!=null){ queue.add(temp.right); } list.add(temp.val); } return list; } public static void main(String []args){ TreeNode root=new TreeNode(1); root.left=new TreeNode(2); root.right=new TreeNode(3); root.left.left=new TreeNode(4); root.left.right=new TreeNode(5); root.right.left=new TreeNode(6); root.right.right=new TreeNode(7); ArrayList<Integer> list=printFromTopToButtom(root); for(int i:list){ System.out.print(i+" "); } } }