一、題目
力扣原題:https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/
二、BFS搜索
/**
* 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>> zigzagLevelOrder(TreeNode root) {
if (null == root) {
return new ArrayList<>();
}
// 保存最終結果
List<List<Integer>> result = new ArrayList<>();
// 保存下一層的節點
List<TreeNode> records = new ArrayList<>();
records.add(root);
// 1 = 向右,2 = 向左
int direction = 1;
while (!records.isEmpty()) {
// 記錄一層結果
List<Integer> subResult = new ArrayList<>();
// 記錄下一層的左右子樹
List<TreeNode> childs = new ArrayList<>();
for (TreeNode node : records) {
if (null != node.left) {
childs.add(node.left);
}
if (null != node.right) {
childs.add(node.right);
}
}
if (direction == 1) {
for (int i = 0; i < records.size(); i++) {
subResult.add(records.get(i).val);
}
direction = 2;
} else if (direction == 2) {
for (int i = records.size() - 1; i >= 0; i--) {
subResult.add(records.get(i).val);
}
direction = 1;
}
// 保存一層結果
result.add(subResult);
// 更新子節點
records = childs;
}
return result;
}
}
- 基本思路:根據題意,很容易想到採用BFS算法。與普通的二叉樹層次遍歷不同的是,需要一個標記爲direction記錄遍歷的方向。
- 時間複雜度:O(n)。BFS搜索,每個節點訪問一次。
- 空間複雜度:O(n)。
三、總結
- 基於題意,很容易想到BFS搜索,另外需要一個變量控制打印的方向。