Problem
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 (Java)
/**
* Definition for a binary tree node.
* public 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;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> q = new LinkedList<>();
q.add(root);
q.add(null);
boolean zig = true;
LinkedList<Integer> level = new LinkedList<>();
while (!q.isEmpty()) {
TreeNode node = q.remove();
while (!q.isEmpty() && node != null) {
if (zig) {
level.add(node.val);
} else {
level.addFirst(node.val);
}
if (node.left != null) {
q.add(node.left);
}
if (node.right != null) {
q.add(node.right);
}
node = q.remove();
}
result.add(level);
zig = !zig;
level = new LinkedList<>();
if (!q.isEmpty()) {
q.add(null);
}
}
return result;
}
}
Solution (Javascript)
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {number[][]}
*/
var zigzagLevelOrder = function(root) {
if (!root) return [];
return helper([[root]], 0);
};
var helper = function (res, level) {
var now = res[level];
var next = [];
for (var i = now.length - 1; i >= 0; i--) {
if (level % 2) {
if (now[i].left) next.push(now[i].left);
if (now[i].right) next.push(now[i].right);
} else {
if (now[i].right) next.push(now[i].right);
if (now[i].left) next.push(now[i].left);
}
now[i] = now[i].val;
}
if (next.length) {
res.push(next);
helper(res, level + 1);
}
return res;
};
Explain:
nope.
Complexity:
- Time complexity : O(n).
- Space complexity : O(n).