Skip to content

Commit 255e3b7

Browse files
committed
https://leetcode.com/problems/kth-smallest-element-in-a-bst/
1 parent 06f1077 commit 255e3b7

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
namespace LeetCodeSolutions.BinarySearchTree;
2+
3+
public class KthSmallestElementInABst
4+
{
5+
public int KthSmallest(TreeNode root, int k)
6+
{
7+
Stack<int> stack = new Stack<int>();
8+
DFS(root, k, stack);
9+
return stack.Pop();
10+
}
11+
12+
private void DFS(TreeNode node, int k, Stack<int> stack)
13+
{
14+
if (node != null)
15+
{
16+
DFS(node.left, k, stack);
17+
if (stack.Count < k)
18+
{
19+
stack.Push(node.val);
20+
DFS(node.right, k, stack);
21+
}
22+
}
23+
}
24+
25+
[Test(Description = "https://leetcode.com/problems/kth-smallest-element-in-a-bst/")]
26+
[Category("Medium")]
27+
[Category("LeetCode")]
28+
[Category("Kth smallest element in a BST")]
29+
[TestCaseSource(nameof(Input))]
30+
[Category("Binary Search Tree")]
31+
[Category("TopInterview")]
32+
public void Test1((int Output, (int?[], int) Input) item)
33+
{
34+
var response = KthSmallest(item.Input.Item1.ToTreeNode(), item.Input.Item2);
35+
Assert.That(response, Is.EqualTo(item.Output));
36+
}
37+
38+
public static IEnumerable<(int Output, (int?[], int) Input)> Input =>
39+
new List<(int, (int?[], int))>()
40+
{
41+
(3, ([5, 3, 6, 2, 4, null, null, 1], 3)),
42+
};
43+
}

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ The Top Interview 150 collection on Leetcode is a curated set of 150 interview q
140140
| 103 | Binary Tree Zigzag Level Order Traversal | Medium ||
141141
| <br> Binary Search Tree<br> | | | |
142142
| 86 | Minimum Absolute Difference in BST | Easy ||
143-
| 87 | Kth Smallest Element in a BST | Medium | |
143+
| 87 | Kth Smallest Element in a BST | Medium | |
144144
| 98 | Validate Binary Search Tree | Medium ||
145145
| <br> Graph General<br> | | | |
146146
| 200 | Number of Islands | Medium ||

0 commit comments

Comments
 (0)