[编程题]把二叉树打印成多行
把二叉树打印成多行
http://www.nowcoder.com/questionTerminal/445c44d982d04483b04a54f298796288
import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; /* 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) { //记录层数 int layer=1; ArrayList<ArrayList<Integer>> result=new ArrayList<ArrayList<Integer>>(); if(pRoot==null){ return result; } //存放奇数层的节点s Queue<TreeNode> s1= new LinkedList<TreeNode>(); s1.offer(pRoot); //存放偶数层节点 Queue<TreeNode> s2= new LinkedList<TreeNode>(); while(!s1.isEmpty()||!s2.isEmpty()){ //奇数层 if(layer%2!=0){ ArrayList<Integer> result1=new ArrayList<Integer>(); while(!s1.isEmpty()){ TreeNode curNode=s1.poll(); if(curNode!=null){ result1.add(curNode.val); s2.offer(curNode.left); s2.offer(curNode.right); } } if(!result1.isEmpty()){ result.add(result1); layer++; } }else{ //偶数层 ArrayList<Integer> result2=new ArrayList<Integer>(); while(!s2.isEmpty()){ TreeNode curNode=s2.poll(); if(curNode!=null){ result2.add(curNode.val); s1.offer(curNode.left); s1.offer(curNode.right); } } if(!result2.isEmpty()){ result.add(result2); layer++; } } } return result; } }