File tree Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change
1
+ import java.util.Stack
2
+ import ds.TreeNode
3
+
4
+ /*
5
+ Definition of TreeNode:
6
+
7
+ data class TreeNode(
8
+ var value: Int,
9
+ var left: TreeNode? = null,
10
+ var right: TreeNode? = null
11
+ )
12
+ */
13
+
14
+ fun kthSmallestNumberInBSTIterative (root : TreeNode ? , k : Int ): Int {
15
+ val stack = Stack <TreeNode >()
16
+ var node = root
17
+ // Copy 'k' to a mutable variable so we can decrement it.
18
+ var k = k
19
+ while (stack.isNotEmpty() || node != null ) {
20
+ // Move to the leftmost node and add nodes to the stack as we go so they
21
+ // can be processed in future iterations.
22
+ while (node != null ) {
23
+ stack.push(node)
24
+ node = node.left
25
+ }
26
+ // Pop the top node from the stack to process it, and decrement 'k'.
27
+ node = stack.pop()
28
+ k--
29
+ // If we have processed 'k' nodes, return the value of the 'k'th smallest
30
+ // node.
31
+ if (k == 0 ) {
32
+ return node.value
33
+ }
34
+ // Move to the right subtree.
35
+ node = node.right
36
+ }
37
+ return - 1
38
+ }
Original file line number Diff line number Diff line change
1
+ /*
2
+ Definition of TreeNode:
3
+
4
+ data class TreeNode(
5
+ var value: Int,
6
+ var left: TreeNode? = null,
7
+ var right: TreeNode? = null
8
+ )
9
+ */
10
+
11
+ fun kthSmallestNumberInBSTRecursive (root : TreeNode ? , k : Int ): Int {
12
+ val sortedList = inorder(root)
13
+ return sortedList[k - 1 ]
14
+ }
15
+
16
+ // Inorder traversal function to attain a sorted list of nodes from the BST.
17
+ fun inorder (node : TreeNode ? ): List <Int > {
18
+ if (node == null ) {
19
+ return emptyList()
20
+ }
21
+ return inorder(node.left) + listOf (node.value) + inorder(node.right)
22
+ }
You can’t perform that action at this time.
0 commit comments