蛇形遍歷二叉樹可以通過層次遍歷來實現。具體步驟如下:
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]