这个题解方法应该没人写吧,代码多,但容易理解,双队列
import java.util.ArrayList; import java.util.Queue; import java.util.LinkedList; /* 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>> target = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> list; if( pRoot == null ) return target; // 双队列法,in和out命名不是很好,但是也懒得改了 Queue<TreeNode> in = new LinkedList<>(); Queue<TreeNode> out = new LinkedList<>(); in.add(pRoot); // in与out双队列来来回回, while ( !in.isEmpty() || !out.isEmpty() ){ list = new ArrayList(); // in输出同时将子节点加入out队列中 while( !in.isEmpty() ){ TreeNode node = in.poll(); list.add(node.val); if( node.left != null ){ out.add(node.left); } if( node.right != null ){ out.add(node.right); } } if( !list.isEmpty() ) target.add(list); list = new ArrayList(); // out输出的同时将子节点加入in中 while( !out.isEmpty() ){ TreeNode node = out.poll(); list.add(node.val); if( node.left != null ){ in.add(node.left); } if( node.right != null ){ in.add(node.right); } } if( !list.isEmpty() ) target.add(list); } return target; } }