【算法训练】LeetCode#103 二叉树的锯齿形层序遍历
一、描述
103. 二叉树的锯齿形层序遍历
给你二叉树的根节点 root
,返回其节点值的 锯齿形层序遍历 。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[20,9],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
二、思路
与#102题类似,不使用递归时,增加了一个辅助栈做变向(双端队列也可以,但是题目中要求的是锯齿形遍历,顺序遍历逆序输出有点取巧了)。
三、解题
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() {}
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public static class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
Deque<TreeNode> oneStack = new LinkedList<>();
Deque<TreeNode> towStack = new LinkedList<>();
List<List<Integer>> lists = new ArrayList<>();
if (root == null){
return lists;
}
oneStack.push(root);
while (!oneStack.isEmpty() || !towStack.isEmpty()){
// 每次完成一层
int level = lists.size(); // 当前遍历层数
lists.add(new ArrayList<>()); // 给每层加空list
if (oneStack.isEmpty()){
while (!towStack.isEmpty()){
TreeNode node = towStack.pop();
lists.get(level).add(node.val);
if (node.right != null) oneStack.push(node.right);
if (node.left != null) oneStack.push(node.left);
}
} else {
while (!oneStack.isEmpty()){
TreeNode node = oneStack.pop();
lists.get(level).add(node.val);
if (node.left != null) towStack.push(node.left);
if (node.right != null) towStack.push(node.right);
}
}
}
return lists;
}
}