103. Binary Tree Zigzag Level Order Traversal

Difficulty:
Related Topics:
Similar Questions:

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

/**
 * 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: