Last active
June 19, 2018 23:14
-
-
Save basekays/345c8cb185e04322744e96198ed7393f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Definition for binary tree | |
| * 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) { | |
| this.stack = []; | |
| while(root) { | |
| this.stack.push(root); | |
| root = root.left; | |
| } | |
| }; | |
| BSTIterator.prototype.hasNext = function() { | |
| return this.stack.length != 0; | |
| }; | |
| BSTIterator.prototype.next = function() { | |
| let subTreeRoot = this.stack.pop(); | |
| let nextVal = subTreeRoot.val; | |
| subTreeRoot = subTreeRoot.right; | |
| while(subTreeRoot) { | |
| this.stack.push(subTreeRoot); | |
| subTreeRoot = subTreeRoot.left; | |
| } | |
| return nextVal; | |
| }; | |
| /* | |
| * Your BSTIterator will be called like this: | |
| * var i = new BSTIterator(root), a = []; | |
| * while (i.hasNext()) a.push(i.next()); | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment