File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
src/main/java/com/fishercoder/solutions Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change 2
2
3
3
import com .fishercoder .common .classes .TreeNode ;
4
4
5
+ import java .util .Deque ;
5
6
import java .util .LinkedList ;
6
7
import java .util .Queue ;
7
8
import java .util .Stack ;
@@ -74,4 +75,33 @@ public int next() {
74
75
}
75
76
}
76
77
}
78
+
79
+ public static class Solution3 {
80
+ /**
81
+ * credit: https://leetcode.com/problems/binary-search-tree-iterator/discuss/52647/Nice-Comparison-(and-short-Solution
82
+ */
83
+ public static class BSTIterator {
84
+ Deque <TreeNode > stack ;
85
+ TreeNode visit ;
86
+
87
+ public BSTIterator (TreeNode root ) {
88
+ stack = new LinkedList <>();
89
+ visit = root ;
90
+ }
91
+
92
+ public int next () {
93
+ while (visit != null ) {
94
+ stack .addLast (visit );
95
+ visit = visit .left ;
96
+ }
97
+ TreeNode next = stack .pollLast ();
98
+ visit = next .right ;
99
+ return next .val ;
100
+ }
101
+
102
+ public boolean hasNext () {
103
+ return visit != null && !stack .isEmpty ();
104
+ }
105
+ }
106
+ }
77
107
}
You can’t perform that action at this time.
0 commit comments