File tree Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Expand file tree Collapse file tree 1 file changed +61
-0
lines changed Original file line number Diff line number Diff line change @@ -43,3 +43,64 @@ BSTIterator.prototype.hasNext = function() {
43
43
* var param_2 = obj.hasNext()
44
44
*/
45
45
46
+ // another
47
+
48
+ /**
49
+ * Definition for a binary tree node.
50
+ * function TreeNode(val) {
51
+ * this.val = val;
52
+ * this.left = this.right = null;
53
+ * }
54
+ */
55
+ /**
56
+ * @param {TreeNode } root
57
+ */
58
+ const BSTIterator = function ( root ) {
59
+ this . generator = dfsGenerator ( root )
60
+ this . root = root
61
+ this . nextSmall = this . generator . next ( ) . value
62
+ }
63
+ function * dfsGenerator ( root ) {
64
+ if ( root === null ) return
65
+ const stack = [ ]
66
+ let current = root
67
+ while ( true ) {
68
+ if ( current ) {
69
+ stack . push ( current )
70
+ current = current . left
71
+ } else if ( stack . length ) {
72
+ const top = stack . pop ( )
73
+ yield top . val
74
+ current = top . right
75
+ } else {
76
+ break
77
+ }
78
+ }
79
+ }
80
+
81
+ /**
82
+ * @return the next smallest number
83
+ * @return {number }
84
+ */
85
+ BSTIterator . prototype . next = function ( ) {
86
+ const smallReturn = this . nextSmall
87
+ this . nextSmall = this . generator . next ( ) . value
88
+ return smallReturn
89
+ }
90
+
91
+ /**
92
+ * @return whether we have a next smallest number
93
+ * @return {boolean }
94
+ */
95
+ BSTIterator . prototype . hasNext = function ( ) {
96
+ return this . nextSmall !== undefined ? true : false
97
+ }
98
+
99
+ /**
100
+ * Your BSTIterator object will be instantiated and called as such:
101
+ * var obj = new BSTIterator(root)
102
+ * var param_1 = obj.next()
103
+ * var param_2 = obj.hasNext()
104
+ */
105
+
106
+
You can’t perform that action at this time.
0 commit comments