剑指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> Print(TreeNode pRoot) { ArrayList > re = new ArrayList<>(); if (pRoot==null) return re; Queue queue = new LinkedList<>(); queue.add(pRoot); int nextLevel =0; int toBePrinted = 1; ArrayList 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; }}