version at: 2022-04-20
/**
* 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;
* }
* }
*/
/**
1. 类似广搜, 用队列维护下, 记录当前层的数量, pop时把下一层都放到队列里
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
List<List<Integer>> results = new ArrayList<>();
if (root != null) queue.add(root);
while (!queue.isEmpty()) {
List<Integer> result = new ArrayList<>();
int count = queue.size();
for (int i = 0; i < count ;i++) {
TreeNode node = queue.poll();
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
result.add(node.val);
}
results.add(result);
}
return results;
}
}
version at: 2020-02-04
/*
1. 按层遍历树,主要是在宽搜的时候分辨出各层的值
2. 记录个数 或 用滚动队列都可以, 记录个数更剩空间
3,记得判空
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if(root == null) return null;
Queue<TreeNode>[] qs = new Queue[2];
qs[0] = new LinkedList<>();
qs[1] = new LinkedList<>();
int cur = 0;
qs[cur].add(root);
// while (!qs[0].isEmpty() && !qs[1].isEmpty()){
while (!qs[0].isEmpty() || !qs[1].isEmpty()){
List<Integer> list = new ArrayList<>();
while(!qs[cur].isEmpty()){
TreeNode node = qs[cur].poll();
list.add(node.val);
if (node.left != null) qs[cur^1].add(node.left);
if (node.right != null) qs[cur^1].add(node.right);
}
cur ^=1;
res.add(list);
}
return res;
}
}