'use strict'

/**
 * Definition for binary tree with next pointer.
 * function TreeLinkNode(val) {
 *     this.val = val;
 *     this.left = this.right = this.next = null;
 * }
 */

function TreeLinkNode(val) {
    this.val = val
    this.left = this.right = this.next = null
}

/**
 * @param {TreeLinkNode} root
 * @return {void} Do not return anything, modify tree in-place instead.
 */
var connect = function (root) {
    // Important! Try to understand all tricks
    while (root) {
        let nextLevelPre = new TreeLinkNode()
        let prev = nextLevelPre
        while (root) {
            if (root.left) {
                prev.next = root.left // nextLevelPre is update here!
                prev = root.left // Then prev moves on, left nextLevelPre unchanged
            }
            if (root.right) {
                prev.next = root.right // The same
                prev = root.right
            }
            root = root.next // Next root
            // Just like:
            //->2   3   4   --\    2 ->3   4
            // / \ / \ / \  --/   / \ / \ / \
        }
        root = nextLevelPre.next // Next level
    }
}

function __main__() {
    /*eslint no-console: ["error", { allow: ["log"] }] */
    const logger = console.log.bind(console)
    //       1
    //      / \
    //     2   3
    //    /    /\
    //   4    6  7
    const n7 = new TreeLinkNode(7)
    const n6 = new TreeLinkNode(6)
    const n4 = new TreeLinkNode(4)
    const n3 = new TreeLinkNode(3)
    n3.left = n6
    n3.right = n7
    const n2 = new TreeLinkNode(2)
    n2.left = n4
    const n1 = new TreeLinkNode(1)
    n1.left = n2
    n1.right = n3
    connect(n1)
    logger(n2)
}

__main__()