-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKthSmallestBST.cs
More file actions
42 lines (39 loc) · 818 Bytes
/
KthSmallestBST.cs
File metadata and controls
42 lines (39 loc) · 818 Bytes
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
// https://leetcode.com/problems/kth-smallest-element-in-a-bst/
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
int count = 0;
int value = 0;
public void Traverse(TreeNode node, int k)
{
if (node.left != null)
{
Traverse(node.left, k);
}
if (++count == k)
{
value = node.val;
}
if (count >= k)
{
return;
}
if (node.right != null)
{
Traverse(node.right, k);
}
}
public int KthSmallest(TreeNode root, int k)
{
Traverse(root, k);
return value;
}
}