蛇形遍历二叉树可以通过层次遍历来实现。具体步骤如下:
leftToRight
,初始值为true
。该变量表示当前行的遍历方向是从左到右还是从右到左。levelList
用来存储当前层的节点值。levelList
中。leftToRight
为true
,则将节点的左右子节点依次入队;如果leftToRight
为false
,则将节点的右左子节点依次入队。levelList
添加到结果列表中,然后将leftToRight
取反,表示下一行的遍历方向。下面是Java代码实现:
import java.util.*;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int val) {
this.val = val;
}
}
public class SnakeTraversal {
public List<List<Integer>> snakeTraversal(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
boolean leftToRight = true;
while (!queue.isEmpty()) {
int levelSize = queue.size();
List<Integer> levelList = new ArrayList<>();
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll();
levelList.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
if (!leftToRight) {
Collections.reverse(levelList);
}
result.add(levelList);
leftToRight = !leftToRight;
}
return result;
}
public static void main(String[] args) {
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.left = new TreeNode(4);
root.left.right = new TreeNode(5);
root.right.left = new TreeNode(6);
root.right.right = new TreeNode(7);
SnakeTraversal snakeTraversal = new SnakeTraversal();
List<List<Integer>> result = snakeTraversal.snakeTraversal(root);
for (List<Integer> level : result) {
System.out.println(level);
}
}
}
输出结果:
[1]
[3, 2]
[4, 5, 6, 7]