102. 二叉树的层序遍历
思路:通过一个队列来记录每一层节点的情况,使用队列的节点大小来记录。
未优化代码
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
Queue<TreeNode> q2 = new LinkedList<>();
q.add(root);
List<List<Integer>> list = new ArrayList<>();
if (root == null) {
return list;
}
List<Integer> temp;
TreeNode treeNode;
boolean flag;
while (!q.isEmpty() || !q2.isEmpty()) {
temp = new ArrayList<>();
flag = false;
// 下面这两个循环只能有一个起作用
while (!q.isEmpty()) {
flag = true;
treeNode = q.poll();
temp.add(treeNode.val);
if (treeNode.left != null) {
q2.add(treeNode.left);
}
if (treeNode.right != null) {
q2.add(treeNode.right);
}
}
while (!q2.isEmpty() && flag == false) {
treeNode = q2.poll();
temp.add(treeNode.val);
if (treeNode.left != null) {
q.add(treeNode.left);
}
if (treeNode.right != null) {
q.add(treeNode.right);
}
}
list.add(temp);
}
return list;
}
List<List<Integer>> ret = new ArrayList<List<Integer>>();
if (root == null) {
return ret;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
List<Integer> level = new ArrayList<Integer>();
int currentLevelSize = queue.size();
for (int i = 1; i <= currentLevelSize; ++i) {
TreeNode node = queue.poll();
level.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
ret.add(level);
}
return ret;
}