思路
用Queue保存一行结点,每次遍历一整行
代码
import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; public class Solution { ArrayList<ArrayList<Integer>> Print(TreeNode pRoot){ ArrayList<ArrayList<Integer>> result = new ArrayList<>(); if(pRoot==null){ return result; } Queue<TreeNode> q = new LinkedList<>(); q.add(pRoot); while (!q.isEmpty()) { ArrayList<Integer> temp = new ArrayList<>(); Queue<TreeNode> tempQ = new LinkedList<>(); while (!q.isEmpty()) { TreeNode t = q.poll(); temp.add(t.val); if(t.left != null){ tempQ.offer(t.left); } if(t.right != null){ tempQ.offer(t.right); } } result.add(temp); q = tempQ; } return result; } }