Skip to content

Commit 8ca86f9

Browse files
committed
add: KthSmallestNumberInBSTRecursive
1 parent 95c1e76 commit 8ca86f9

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import java.util.ArrayList;
2+
import java.util.List;
3+
4+
import DS.TreeNode;
5+
6+
/*
7+
// Definition of TreeNode:
8+
class TreeNode {
9+
public int val;
10+
public TreeNode left;
11+
public TreeNode right;
12+
public TreeNode(int val) {
13+
this.val = val;
14+
}
15+
}
16+
*/
17+
18+
public class KthSmallestNumberInBSTRecursive {
19+
public int kthSmallestNumberInBSTRecursive(TreeNode root, int k) {
20+
List<Integer> sortedList = new ArrayList<>();
21+
inorder(root, sortedList);
22+
return sortedList.get(k - 1);
23+
}
24+
25+
// Inorder traversal function to attain a sorted list of nodes from the BST.
26+
private void inorder(TreeNode node, List<Integer> sortedList) {
27+
if (node == null) {
28+
return;
29+
}
30+
inorder(node.left, sortedList);
31+
sortedList.add(node.val);
32+
inorder(node.right, sortedList);
33+
}
34+
}

0 commit comments

Comments
 (0)