58、把二叉树打印成多行
一、题目
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
二、解法
1 import java.util.ArrayList; 2 import java.util.LinkedList; 3 import java.util.Queue; 4 5 /* 6 public class TreeNode { 7 int val = 0; 8 TreeNode left = null; 9 TreeNode right = null; 10 11 public TreeNode(int val) { 12 this.val = val; 13 } 14 15 } 16 */ 17 public class Solution { 18 /*ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { 19 ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); 20 depth(pRoot,1,list); 21 return list; 22 } 23 private void depth(TreeNode root,int depth,ArrayList<ArrayList<Integer>> list){ 24 if(root == null) 25 return; 26 if(depth > list.size()) 27 list.add(new ArrayList<Integer>()); 28 list.get(depth-1).add(root.val); 29 depth(root.left,depth+1,list); 30 depth(root.right,depth+1,list); 31 }*/ 32 ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) { 33 ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>(); 34 if(pRoot == null) 35 return al; 36 //使用队列 37 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 38 queue.add(pRoot); 39 while(!queue.isEmpty()){ 40 ArrayList<Integer> list = new ArrayList<Integer>();//存储一行 41 int size = queue.size(); 42 int start = 0; 43 while(start++ < size){ 44 TreeNode t = queue.poll(); 45 if(t.left != null) 46 queue.add(t.left); 47 if(t.right != null) 48 queue.add(t.right); 49 list.add(t.val); 50 } 51 al.add(list); 52 } 53 return al; 54 } 55 56 }