1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- 'use strict'
- /**
- * Definition for binary tree
- * function TreeNode(val) {
- * this.val = val;
- * this.left = this.right = null;
- * }
- */
- function TreeNode(val) {
- this.val = val
- this.left = this.right = null
- }
- /**
- * @constructor
- * @param {TreeNode} root - root of the binary search tree
- */
- var BSTIterator = function (root) {
- const stack = []
- this.array = []
- let curr = root
- while (stack.length !== 0 || curr !== null) {
- while (curr !== null) {
- stack.push(curr)
- curr = curr.left
- }
- if (stack.length !== 0) {
- curr = stack.pop()
- this.array.push(curr.val)
- curr = curr.right
- }
- }
- }
- /**
- * @this BSTIterator
- * @returns {boolean} - whether we have a next smallest number
- */
- BSTIterator.prototype.hasNext = function () {
- return this.array.length !== 0
- }
- /**
- * @this BSTIterator
- * @returns {number} - the next smallest number
- */
- BSTIterator.prototype.next = function () {
- return this.array.shift()
- }
- /**
- * Your BSTIterator will be called like this:
- * var i = new BSTIterator(root), a = [];
- * while (i.hasNext()) a.push(i.next());
- */
- function __main__() {
- /* eslint no-console: ["error", {"allow": ["log"]}] */
- const logger = console.log.bind(console)
- // 1
- // / \
- // 2 3
- // / /\
- // 4 6 7
- const n7 = new TreeNode(7)
- const n6 = new TreeNode(6)
- const n4 = new TreeNode(4)
- const n3 = new TreeNode(3)
- n3.left = n6
- n3.right = n7
- const n2 = new TreeNode(2)
- n2.left = n4
- const n1 = new TreeNode(1)
- n1.left = n2
- n1.right = n3
- const i = new BSTIterator(n1)
- const a = []
- while (i.hasNext()) {
- a.push(i.next())
- }
- logger(a)
- }
- __main__()
|