File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ package leetcode ;
2+
3+ import java .util .Stack ;
4+
5+ /**
6+ * Project Name : Leetcode
7+ * Package Name : leetcode
8+ * File Name : BinarySearchTreeIterator
9+ * Creator : Leo
10+ * Description : TODO
11+ */
12+ public class BinarySearchTreeIterator {
13+ /**
14+ * 173. Binary Search Tree Iterator
15+ *
16+ * time : O(n)
17+ * @param root
18+ */
19+
20+ private TreeNode cur ;
21+ private Stack <TreeNode > stack ;
22+
23+ public BinarySearchTreeIterator (TreeNode root ) {
24+ cur = root ;
25+ stack = new Stack <>();
26+ }
27+
28+ /** @return whether we have a next smallest number */
29+ public boolean hasNext () {
30+ if (!stack .isEmpty () || cur != null ) return true ;
31+ return false ;
32+ }
33+
34+ /** @return the next smallest number */
35+ public int next () {
36+ while (cur != null ) {
37+ stack .push (cur );
38+ cur = cur .left ;
39+ }
40+ cur = stack .pop ();
41+ int val = cur .val ;
42+ cur = cur .right ;
43+ return val ;
44+ }
45+ }
You can’t perform that action at this time.
0 commit comments