Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 07d09a0

Browse files
add a solution for 173
1 parent 76d2c52 commit 07d09a0

File tree

1 file changed

+30
-0
lines changed
  • src/main/java/com/fishercoder/solutions

1 file changed

+30
-0
lines changed

src/main/java/com/fishercoder/solutions/_173.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import com.fishercoder.common.classes.TreeNode;
44

5+
import java.util.Deque;
56
import java.util.LinkedList;
67
import java.util.Queue;
78
import java.util.Stack;
@@ -74,4 +75,33 @@ public int next() {
7475
}
7576
}
7677
}
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+
}
77107
}

0 commit comments

Comments
 (0)