File tree Expand file tree Collapse file tree 1 file changed +41
-1
lines changed Expand file tree Collapse file tree 1 file changed +41
-1
lines changed Original file line number Diff line number Diff line change @@ -23,7 +23,7 @@ Calling next() will return the next smallest number in the BST.
23
23
* }
24
24
*/
25
25
26
- public class BSTIterator {
26
+ public class BSTIterator_1 {
27
27
28
28
public BSTIterator (TreeNode root ) {
29
29
stk = new Stack <TreeNode >();
@@ -53,6 +53,46 @@ public int next() {
53
53
private TreeNode node ;
54
54
}
55
55
56
+
57
+ public class BSTIterator_2 {
58
+
59
+ public BSTIterator (TreeNode root ) {
60
+ node = root ;
61
+ }
62
+
63
+ /** @return whether we have a next smallest number */
64
+ public boolean hasNext () {
65
+ return node != null ;
66
+ }
67
+
68
+ /** @return the next smallest number */
69
+ public int next () {
70
+ if (node == null ) return 0 ;
71
+ int res = 0 ;
72
+ while (node != null ) {
73
+ if (node .left == null ) {
74
+ res = node .val ;
75
+ node = node .right ;
76
+ return res ;
77
+ }
78
+ TreeNode pre = node .left ;
79
+ while (pre .right != null && pre .right != node )
80
+ pre = pre .right ;
81
+ if (pre .right == null ) {
82
+ pre .right = node ;
83
+ node = node .left ;
84
+ } else {
85
+ res = node .val ;
86
+ node = node .right ;
87
+ pre .right = null ;
88
+ return res ;
89
+ }
90
+ }
91
+ return res ;
92
+ }
93
+ private TreeNode node ;
94
+ }
95
+
56
96
/**
57
97
* Your BSTIterator will be called like this:
58
98
* BSTIterator i = new BSTIterator(root);
You can’t perform that action at this time.
0 commit comments