Given a binary tree, return the zigzag level order traversal of its nodes’ values. (ie, from left to right, then right to left for the next level and alternate between).
For example:
Given binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
Solution:
Using two stacks.
While stack1 is not empty. Adding the node value to the result list, and pushing the left node and then right node into the stack2.
While stack2 is not empty. Adding the node value to the result list, and pushing the right node and then left node into the stack1.
/**
* 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) {
Stack<TreeNode> stackOne = new Stack<>();
Stack<TreeNode> stackTwo = new Stack<>();
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (root == null) {
return res;
}
stackOne.push(root);
while (!stackOne.isEmpty() || !stackTwo.isEmpty()) {
List<Integer> level = new ArrayList<>();
while (!stackOne.isEmpty()) {
TreeNode node = stackOne.pop();
level.add(node.val);
if (node.left != null) {
stackTwo.push(node.left);
}
if (node.right != null) {
stackTwo.push(node.right);
}
}
res.add(level);
level = new ArrayList<>();
while (!stackTwo.isEmpty()) {
TreeNode node = stackTwo.pop();
level.add(node.val);
if (node.right != null) {
stackOne.push(node.right);
}
if (node.left != null) {
stackOne.push(node.left);
}
}
if (level.size() != 0) {
res.add(level);
}
}
return res;
}
}