File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments