描述
给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行)
样例
给出一棵二叉树 {3,9,20,#,#,15,7}
3
/ \
9 20
/ \
15 7
返回其锯齿形的层次遍历为:
[
[3],
[20,9],
[15,7]
]
代码
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param root: A Tree
* @return: A list of lists of integer include the zigzag level order traversal of its nodes' values.
*/
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Stack<TreeNode> currLevel = new Stack<TreeNode>();
Stack<TreeNode> nextLevel = new Stack<TreeNode>();
// 不需要新建栈
Stack<TreeNode> tmp;
currLevel.push(root);
// normal代表当前层顺序是不是从左往右
boolean normalOrder = true;
// 因为curLevel和nextLevel不断来回交换,第一个while用于判断树是否遍历完最后一层
while (!currLevel.isEmpty()) {
// 每一层都要新建一个动态数组存储当前层的值
ArrayList<Integer> currLevelResult = new ArrayList<Integer>();
// 第二个while用于判断当前层结点是否遍历完成
while (!currLevel.isEmpty()) {
TreeNode node = currLevel.pop();
currLevelResult.add(node.val);
// 栈的弹出是反的,当前层正常顺序,下一层先压左后压右,先弹右后弹左
if (normalOrder) {
if (node.left != null) {
nextLevel.push(node.left);
}
if (node.right != null) {
nextLevel.push(node.right);
}
} else {
if (node.right != null) {
nextLevel.push(node.right);
}
if (node.left != null) {
nextLevel.push(node.left);
}
}
}
result.add(currLevelResult);
// 交换两个栈的引用指向,当前栈要pop成空栈,子结点加入到nextLevel
tmp = currLevel;
currLevel = nextLevel;
nextLevel = tmp;
normalOrder = !normalOrder;
}
return result;
}
}