117.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict'
  2. /**
  3. * Definition for binary tree with next pointer.
  4. * function TreeLinkNode(val) {
  5. * this.val = val;
  6. * this.left = this.right = this.next = null;
  7. * }
  8. */
  9. function TreeLinkNode(val) {
  10. this.val = val
  11. this.left = this.right = this.next = null
  12. }
  13. /**
  14. * @param {TreeLinkNode} root
  15. * @return {void} Do not return anything, modify tree in-place instead.
  16. */
  17. var connect = function (root) {
  18. // Important! Try to understand all tricks
  19. while (root) {
  20. let nextLevelPre = new TreeLinkNode()
  21. let prev = nextLevelPre
  22. while (root) {
  23. if (root.left) {
  24. prev.next = root.left // nextLevelPre is update here!
  25. prev = root.left // Then prev moves on, left nextLevelPre unchanged
  26. }
  27. if (root.right) {
  28. prev.next = root.right // The same
  29. prev = root.right
  30. }
  31. root = root.next // Next root
  32. // Just like:
  33. //->2 3 4 --\ 2 ->3 4
  34. // / \ / \ / \ --/ / \ / \ / \
  35. }
  36. root = nextLevelPre.next // Next level
  37. }
  38. }
  39. function __main__() {
  40. /*eslint no-console: ["error", { allow: ["log"] }] */
  41. let logger = console.log.bind(console)
  42. // 1
  43. // / \
  44. // 2 3
  45. // / /\
  46. // 4 6 7
  47. let n7 = new TreeLinkNode(7)
  48. let n6 = new TreeLinkNode(6)
  49. let n4 = new TreeLinkNode(4)
  50. let n3 = new TreeLinkNode(3)
  51. n3.left = n6
  52. n3.right = n7
  53. let n2 = new TreeLinkNode(2)
  54. n2.left = n4
  55. let n1 = new TreeLinkNode(1)
  56. n1.left = n2
  57. n1.right = n3
  58. connect(n1)
  59. logger(n2)
  60. }
  61. __main__()