123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- '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"] }] */
- let logger = console.log.bind(console)
- // 1
- // / \
- // 2 3
- // / /\
- // 4 6 7
- let n7 = new TreeLinkNode(7)
- let n6 = new TreeLinkNode(6)
- let n4 = new TreeLinkNode(4)
- let n3 = new TreeLinkNode(3)
- n3.left = n6
- n3.right = n7
- let n2 = new TreeLinkNode(2)
- n2.left = n4
- let n1 = new TreeLinkNode(1)
- n1.left = n2
- n1.right = n3
- connect(n1)
- logger(n2)
- }
- __main__()
|