173.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. 'use strict'
  2. /**
  3. * Definition for binary tree
  4. * function TreeNode(val) {
  5. * this.val = val;
  6. * this.left = this.right = null;
  7. * }
  8. */
  9. function TreeNode(val) {
  10. this.val = val
  11. this.left = this.right = null
  12. }
  13. /**
  14. * @constructor
  15. * @param {TreeNode} root - root of the binary search tree
  16. */
  17. var BSTIterator = function (root) {
  18. const stack = []
  19. this.array = []
  20. let curr = root
  21. while (stack.length !== 0 || curr !== null) {
  22. while (curr !== null) {
  23. stack.push(curr)
  24. curr = curr.left
  25. }
  26. if (stack.length !== 0) {
  27. curr = stack.pop()
  28. this.array.push(curr.val)
  29. curr = curr.right
  30. }
  31. }
  32. }
  33. /**
  34. * @this BSTIterator
  35. * @returns {boolean} - whether we have a next smallest number
  36. */
  37. BSTIterator.prototype.hasNext = function () {
  38. return this.array.length !== 0
  39. }
  40. /**
  41. * @this BSTIterator
  42. * @returns {number} - the next smallest number
  43. */
  44. BSTIterator.prototype.next = function () {
  45. return this.array.shift()
  46. }
  47. /**
  48. * Your BSTIterator will be called like this:
  49. * var i = new BSTIterator(root), a = [];
  50. * while (i.hasNext()) a.push(i.next());
  51. */
  52. function __main__() {
  53. /* eslint no-console: ["error", {"allow": ["log"]}] */
  54. const logger = console.log.bind(console)
  55. // 1
  56. // / \
  57. // 2 3
  58. // / /\
  59. // 4 6 7
  60. const n7 = new TreeNode(7)
  61. const n6 = new TreeNode(6)
  62. const n4 = new TreeNode(4)
  63. const n3 = new TreeNode(3)
  64. n3.left = n6
  65. n3.right = n7
  66. const n2 = new TreeNode(2)
  67. n2.left = n4
  68. const n1 = new TreeNode(1)
  69. n1.left = n2
  70. n1.right = n3
  71. const i = new BSTIterator(n1)
  72. const a = []
  73. while (i.hasNext()) {
  74. a.push(i.next())
  75. }
  76. logger(a)
  77. }
  78. __main__()