Skip to content

Commit 0c05a1e

Browse files
Jer3myYuaikhelis
authored andcommitted
add: KthSmallestNumberInBSTIterative
1 parent a289665 commit 0c05a1e

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import java.util.Stack;
2+
3+
import DS.TreeNode;
4+
5+
/*
6+
// Definition of TreeNode:
7+
class TreeNode {
8+
public int val;
9+
public TreeNode left;
10+
public TreeNode right;
11+
public TreeNode(int val) {
12+
this.val = val;
13+
}
14+
}
15+
*/
16+
17+
public class KthSmallestNumberInBSTIterative {
18+
public int kthSmallestNumberInBSTIterative(TreeNode root, int k) {
19+
Stack<TreeNode> stack = new Stack<>();
20+
TreeNode node = root;
21+
while (!stack.isEmpty() || node != null) {
22+
// Move to the leftmost node and add nodes to the stack as we go so they
23+
// can be processed in future iterations.
24+
while (node != null) {
25+
stack.push(node);
26+
node = node.left;
27+
}
28+
// Pop the top node from the stack to process it, and decrement 'k'.
29+
node = stack.pop();
30+
k--;
31+
// If we have processed 'k' nodes, return the value of the 'k'th smallest
32+
// node.
33+
if (k == 0) {
34+
return node.val;
35+
}
36+
// Move to the right subtree.
37+
node = node.right;
38+
}
39+
return -1;
40+
}
41+
}

0 commit comments

Comments
 (0)