|
@@ -9,8 +9,8 @@
|
|
|
*/
|
|
|
|
|
|
function TreeNode(val) {
|
|
|
- this.val = val;
|
|
|
- this.left = this.right = null;
|
|
|
+ this.val = val
|
|
|
+ this.left = this.right = null
|
|
|
}
|
|
|
|
|
|
/**
|
|
@@ -18,7 +18,20 @@ function TreeNode(val) {
|
|
|
* @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
|
|
|
+ }
|
|
|
+ }
|
|
|
}
|
|
|
|
|
|
/**
|
|
@@ -26,7 +39,7 @@ var BSTIterator = function (root) {
|
|
|
* @returns {boolean} - whether we have a next smallest number
|
|
|
*/
|
|
|
BSTIterator.prototype.hasNext = function () {
|
|
|
-
|
|
|
+ return this.array.length !== 0
|
|
|
}
|
|
|
|
|
|
/**
|
|
@@ -34,7 +47,7 @@ BSTIterator.prototype.hasNext = function () {
|
|
|
* @returns {number} - the next smallest number
|
|
|
*/
|
|
|
BSTIterator.prototype.next = function () {
|
|
|
-
|
|
|
+ return this.array.shift()
|
|
|
}
|
|
|
|
|
|
/**
|
|
@@ -44,22 +57,22 @@ BSTIterator.prototype.next = function () {
|
|
|
*/
|
|
|
|
|
|
function __main__() {
|
|
|
- /* eslit no-console: ["error", {"allow": ["log"]}] */
|
|
|
+ /* 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)
|
|
|
+ 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 TreeLinkNode(2)
|
|
|
+ const n2 = new TreeNode(2)
|
|
|
n2.left = n4
|
|
|
- const n1 = new TreeLinkNode(1)
|
|
|
+ const n1 = new TreeNode(1)
|
|
|
n1.left = n2
|
|
|
n1.right = n3
|
|
|
const i = new BSTIterator(n1)
|