GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • LeetCodeJavascript.com
  • Star on GitHub

This view

  • Original page
  • New address

GeezerVison is showing leetcodejavascript.com — #103 - Binary Tree Zigzag Level Order Traversal - LeetCode JavaScript Solutions

Back to all solutions

#103 - Binary Tree Zigzag Level Order Traversal

Medium • View on LeetCode • View on GitHub
Tree Breadth-First Search Binary Tree

Problem Description

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).

Solution

/**
 * 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) {
  const result = [];

  function traverse(node, depth) {
    if (node == null) return;
    if (result[depth] == null) result[depth] = [];

    if (depth % 2 === 0) {
      result[depth].push(node.val);
    } else {
      result[depth].unshift(node.val);
    }

    traverse(node.left, depth + 1);
    traverse(node.right, depth + 1);
  }

  traverse(root, 0);

  return result;
};
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.