看了题解,没有思路跟我一样的,就补一个,哈哈哈哈哈哈
如图
import java.util.Queue; import java.util.LinkedList; import java.util.Stack; public class Solution { public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> result = new ArrayList<>(); if(pRoot == null) return result; Stack<TreeNode> tmp = new Stack<>(); Stack<TreeNode> tmp1 = new Stack<>(); tmp.add(pRoot); while(tmp.size() > 0 || tmp1.size() > 0) { ArrayList<Integer> flood = new ArrayList<>(); if(tmp.size() > 0) { int size = tmp.size(); for(int i=0; i<size; i++) { TreeNode pop = tmp.pop(); flood.add(pop.val); if(pop.left != null) { tmp1.add(pop.left); } if(pop.right != null) { tmp1.add(pop.right); } } result.add(flood); continue; } if(tmp1.size() > 0) { int size = tmp1.size(); for(int i=0; i<size; i++) { TreeNode pop = tmp1.pop(); flood.add(pop.val); if(pop.right != null) { tmp.add(pop.right); } if(pop.left != null) { tmp.add(pop.left); } } result.add(flood); continue; } } return result; } }