DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Binary Tree Zigzag Level Order Traversal

Given the root of a binary tree, return the zigzag level order traversal of its nodes' values. (i.e., from left to right, then right to left for the next level and alternate between).

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: [[3],[20,9],[15,7]]

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number[][]}
 */
var zigzagLevelOrder = function (root) {
  if (!root) return [];
  let queue = [root];
  let levels = [];
  while (queue.length > 0) {
    let levelSize = queue.length;
    levels.push([]);
    for (let i = 0; i < levelSize; i++) {
      let curr = queue.shift();
      if (levels.length % 2 == 1) levels[levels.length - 1].push(curr.val);
      else levels[levels.length - 1].unshift(curr.val);

      if (curr.left) queue.push(curr.left);
      if (curr.right) queue.push(curr.right);
    }
  }

  return levels;
};

Enter fullscreen mode Exit fullscreen mode

Solution 2 : via Recurssion

var zigzagLevelOrder = function(root, res = [], lvl = 0) {
    if(!root) return res;

    if(!res[lvl]){
        res[lvl] = [];
    }
    if(lvl%2==0)
        res[lvl].push(root.val);
    else
        res[lvl].unshift(root.val);

    zigzagLevelOrder(root.left, res, lvl+1);
    zigzagLevelOrder(root.right, res, lvl+1);

    return res;
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)