-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathp230.c
37 lines (35 loc) · 817 Bytes
/
p230.c
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
struct TreeNode* f(struct TreeNode *root, int k, int *count) {
struct TreeNode *result = NULL;
int cntl = 0;
int cntr = 0;
if (root->left != NULL)
{
result = f(root->left, k, &cntl);
if (result != NULL) return result;
}
if (k == cntl+1)
{
result = root;
return result;
}
if (root->right != NULL)
{
result = f(root->right, k-cntl-1, &cntr);
if (result != NULL) return result;
}
(*count) = cntl+1+cntr;
return NULL;
}
int kthSmallest(struct TreeNode* root, int k) {
int count = 0;
struct TreeNode *result = f(root, k, &count);
return result->val;
}