剑指Offer:二叉树打印成多行【23】
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
题目分析
Java题解
package tree; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; public class PrintByLevel { public static void main(String[] args) { TreeNode t1 = new TreeNode(1); TreeNode t2 = new TreeNode(2); TreeNode t3 = new TreeNode(3); TreeNode t4 = new TreeNode(4); TreeNode t5 = new TreeNode(5); t1.left=t2; t1.right=t3; t2.left=t4; t2.right=t5; } static ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> re = new ArrayList<>(); if (pRoot==null) return re; Queue<TreeNode> queue = new LinkedList<>(); queue.add(pRoot); int nextLevel =0; int toBePrinted = 1; ArrayList<Integer> cuLevel = new ArrayList<>(); while (!queue.isEmpty()) { TreeNode tmp = queue.poll(); cuLevel.add(tmp.val); if(tmp.left!=null) { queue.add(tmp.left); nextLevel++; } if(tmp.right!=null) { queue.add(tmp.right); nextLevel++; } toBePrinted--; if(toBePrinted==0) { re.add(cuLevel); cuLevel = new ArrayList<>(); toBePrinted = nextLevel; nextLevel=0; } } return re; } }