标签:打印二叉树 null code 剑指offer sub import util port public
60. 把二叉树打印成多行
层序遍历即可
1 import java.util.Queue; 2 import java.util.LinkedList; 3 public class Solution { 4 ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { 5 ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>(); 6 if(pRoot == null){ 7 return list; 8 } 9 // 层序遍历 10 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 11 queue.offer(pRoot); 12 TreeNode top; 13 while(!queue.isEmpty()){ 14 int count = queue.size(); 15 ArrayList<Integer> innerList = new ArrayList<Integer>(); 16 for(int i = 0; i < count; i++){ 17 top = queue.poll(); 18 innerList.add(top.val); 19 if(top.left != null) 20 queue.offer(top.left); 21 if(top.right != null) 22 queue.offer(top.right); 23 } 24 list.add(innerList); 25 } 26 return list; 27 } 28 29 }
标签:打印二叉树 null code 剑指offer sub import util port public
原文地址:https://www.cnblogs.com/hi3254014978/p/12444900.html