generated from eyamenko/dotnet-template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem39.cs
More file actions
49 lines (41 loc) · 1.22 KB
/
Problem39.cs
File metadata and controls
49 lines (41 loc) · 1.22 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
namespace LeetCode;
/// <summary>
/// <see href="https://leetcode.com/problems/kth-smallest-element-in-a-bst/">Kth Smallest Element in a BST</see>.
/// </summary>
public static class Problem39
{
/// <summary>
/// Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.
/// Time complexity: O(n).
/// Space complexity: O(n).
/// </summary>
/// <param name="root">Binary search tree to traverse.</param>
/// <param name="k">Kth smallest element to return.</param>
/// <returns>Kth smallest element.</returns>
public static int KthSmallest(TreeNode root, int k)
{
var stack = new Stack<int>();
if (Traverse(root, k, stack))
{
return stack.Peek();
}
return -1;
}
private static bool Traverse(TreeNode? node, int k, Stack<int> stack)
{
if (node == null)
{
return false;
}
if (Traverse(node.Left, k, stack))
{
return true;
}
stack.Push(node.Val);
if (stack.Count == k)
{
return true;
}
return Traverse(node.Right, k, stack);
}
}