71. 二叉树的锯齿形层次遍历
给出一棵二叉树,返回其节点值的锯齿形层次遍历(先从左往右,下一层再从右往左,层与层之间交替进行)
样例
样例 1:
输入:{1,2,3}
输出:[[1],[3,2]]
解释:
1
/ \
2 3
它将被序列化为 {1,2,3}
样例 2:
输入:{3,9,20,#,#,15,7}
输出:[[3],[20,9],[15,7]]
解释:
3
/ \
9 20
/ \
15 7
它将被序列化为 {3,9,20,#,#,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 treeNode) {
List<List<Integer>> ret = new ArrayList<>();
if (treeNode == null) return ret;
Queue<TreeNode> stack = new LinkedList<>();
stack.add(treeNode);
boolean flag = true;
while (!stack.isEmpty()) {
List<Integer> integerList = new ArrayList<>();
Queue<TreeNode> stack2 = new LinkedList<>();
while (!stack.isEmpty()) {
treeNode = stack.poll();
if (flag) {
integerList.add(treeNode.val);
} else {
integerList.add(0, treeNode.val);
}
// if (flag) {
if (treeNode.left != null) {
stack2.add(treeNode.left);
}
if (treeNode.right != null) {
stack2.add(treeNode.right);
}
// }else {
// if (treeNode.right != null) {
// stack2.add(treeNode.right);
// }
// if (treeNode.left != null) {
// stack2.add(treeNode.left);
// }
// }
}
if (flag) {
flag = false;
} else {
flag = true;
}
stack = stack2;
if (!integerList.isEmpty()) {
ret.add(integerList);
}
}
return ret;
}
}