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 — #117 - Populating Next Right Pointers in Each Node II - LeetCode JavaScript Solutions

Back to all solutions

#117 - Populating Next Right Pointers in Each Node II

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

Problem Description

Given a binary tree, populate each next pointer to point to its next right node.

If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Solution

/**
 * // Definition for a _Node.
 * function _Node(val, left, right, next) {
 *    this.val = val === undefined ? null : val;
 *    this.left = left === undefined ? null : left;
 *    this.right = right === undefined ? null : right;
 *    this.next = next === undefined ? null : next;
 * };
 */

/**
 * @param {_Node} root
 * @return {_Node}
 */
var connect = function(root) {
  if (root === null) return root;

  const depth = 0;
  const stack = [[root, depth]];

  while (stack.length) {
    const [node, depth] = stack.shift();
    if (stack.length) {
      const [nextNode, nextDepth] = stack[0];
      if (depth === nextDepth) {
        node.next = nextNode;
      }
    }
    if (node.left) {
      stack.push([node.left, depth + 1]);
    }
    if (node.right) {
      stack.push([node.right, depth + 1]);
    }
  }

  return root;
};
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.