File tree 1 file changed +15
-13
lines changed
1 file changed +15
-13
lines changed Original file line number Diff line number Diff line change 14
14
* }
15
15
*/
16
16
class BSTIterator {
17
- Stack <TreeNode > stack ;
17
+
18
+ private Stack <TreeNode > stack ;
19
+
18
20
public BSTIterator (TreeNode root ) {
19
- stack = new Stack <>();
20
- while (root != null ) {
21
- stack .push (root );
22
- root = root .left ;
23
- }
21
+ this .stack = new Stack <>();
22
+ updateStack (root );
24
23
}
25
24
26
25
public int next () {
27
- TreeNode node = stack .pop ();
28
- TreeNode rightNode = node .right ;
29
- while (rightNode != null ) {
30
- stack .push (rightNode );
31
- rightNode = rightNode .left ;
32
- }
26
+ TreeNode node = this .stack .pop ();
27
+ updateStack (node .right );
33
28
return node .val ;
34
29
}
35
30
36
31
public boolean hasNext () {
37
- return !stack .isEmpty ();
32
+ return !this .stack .isEmpty ();
33
+ }
34
+
35
+ private void updateStack (TreeNode node ) {
36
+ while (node != null ) {
37
+ this .stack .push (node );
38
+ node = node .left ;
39
+ }
38
40
}
39
41
}
40
42
You can’t perform that action at this time.
0 commit comments