public class BinaryTree { public static void main(String[] args) { TreeNode root = new TreeNode( new TreeNode( new TreeNode(4), new TreeNode(5), 2), new TreeNode( new TreeNode(6), new TreeNode(7), 3), 1); //方式1 print1(root); //方式2 List<List<Integer>> list = print2(root); } public static List<List<Integer>> print2(TreeNode root){ List<List<Integer>>list=new ArrayList<>(); if(root==null){ return list; } LinkedListQueue<TreeNode> queue = new LinkedListQueue<>(); queue.offer(root); int count1 = 1; while (!queue.isEmpty()) { List<Integer>leave=new ArrayList<>(); int count2 = 0;//下层节点数 for (int i = 0; i < count1; i++) { TreeNode pool = queue.pool(); leave.add(pool.val); System.out.print(pool + " "); if (pool.left != null) { queue.offer(pool.left); count2++; } if (pool.right != null) { queue.offer(pool.right); count2++; } } System.out.println(); list.add(leave); count1=count2; } return list; } public static void print1(TreeNode root){ LinkedListQueue<TreeNode> queue = new LinkedListQueue<>(); queue.offer(root); int count1 = 1; while (!queue.isEmpty()) { int count2 = 0;//下层节点数 for (int i = 0; i < count1; i++) { TreeNode pool = queue.pool(); System.out.print(pool + " "); if (pool.left != null) { queue.offer(pool.left); count2++; } if (pool.right != null) { queue.offer(pool.right); count2++; } } System.out.println(); count1=count2; } } static class TreeNode { TreeNode left; TreeNode right; int val; public TreeNode(int val) { this.val = val; } public TreeNode(TreeNode left, TreeNode right, int val) { this.left = left; this.right = right; this.val = val; } @Override public String toString() { return String.valueOf(this.val); } } }
y