二叉树层序遍历介绍
首先将每一层的节点放入一个队列中,然后遍历这个队列,同时将遍历到的节点的子节点也加入到队列中,直到队列为空。
基本模版:
void traverse(TreeNode root) {
if (root == null) return;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
TreeNode cur = q.poll();
System.out.println(cur.val);
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
}
}
如果过程中需要分别得到每一层的各元素,则可改为:
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
if (root == null) return res;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
int count = q.size();
for (int i = 0; i < count; i++) {
TreeNode cur = q.poll();
System.out.println(cur.val);
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
}
}
return res;
}
思路
本题需要锯齿形层序遍历二叉树(先从左到右,再从右到左,依次循环) 根据题意可知,奇数行从左到右遍历,偶数行从右到左遍历 所以在奇数行正常得到遍历序列加入结果集;而偶数行则要先将遍历序列反转然后再加入结果集
代码实现(java)
class Solution {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
if (root == null) return res;
int leave = 0;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while (!q.isEmpty()) {
int count = q.size();
List<Integer> temp = new ArrayList<>();
leave++;
for (int i = 0; i < count; i++) {
TreeNode cur = q.poll();
temp.add(cur.val);
if (cur.left != null) q.offer(cur.left);
if (cur.right != null) q.offer(cur.right);
}
if (leave % 2 == 0) {
Collections.reverse(temp);
}
res.add(temp);
}
return res;
}
}
|