把二叉树打印成多行
把二叉树打印成多行
http://www.nowcoder.com/questionTerminal/445c44d982d04483b04a54f298796288
import java.util.*; /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> result = new ArrayList<>(); if(pRoot==null){ return result; } Queue<TreeNode> queue = new LinkedList<>(); queue.add(pRoot); int sum = 1;//当前层的元素个数为1; while(queue.size()!=0){ ArrayList<Integer> list = new ArrayList<>(); while(sum>0){ TreeNode t = queue.poll(); list.add(t.val); if(t.left!=null){ queue.add(t.left); } if(t.right!=null){ queue.add(t.right); } sum--; } sum = queue.size(); result.add(list); } return result; } }