题目
思路
利用一个队列来辅助进行层序遍历
口诀:入队出队访问,有左入左,有右入右。这样方便记忆。具体位置请看代码注释。
因为题目要求把一层的输出到一个list里。所以我们要在while(!queue.isEmpty()) 循环一开始设置一个len表示这一层中有几个节点。
代码
//leetcode submit region begin(Prohibit modification and deletion)
import java.util.ArrayList;
import java.util.LinkedList;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (root == null)
return res;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root); //入队
while (!queue.isEmpty()) {
List<Integer> item = new ArrayList<Integer>();
int len = queue.size();
while (len > 0) {
TreeNode temp = queue.poll(); //出队
item.add(temp.val); //访问
if (temp.left != null) //有左入左
queue.add(temp.left);
if (temp.right != null) //有右入右
queue.add(temp.right);
len--;
}
res.add(item);
}
return res;
}
}
//leetcode submit region end(Prohibit modification and deletion)