-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path230_kth_smallest_element_in_a_bst.c
50 lines (44 loc) · 1.22 KB
/
230_kth_smallest_element_in_a_bst.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
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <assert.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct List {
int* vals;
int size;
int top;
};
void inorderTraversal(struct TreeNode* node, struct List* list) {
if(node->left != NULL)
inorderTraversal(node->left, list);
list->vals[list->top++] = node->val;
if(node->right != NULL)
inorderTraversal(node->right, list);
}
int kthSmallest(struct TreeNode* root, int k) {
struct List* list = (struct List *)malloc(sizeof(struct List));
int size = 10000;
list->vals = (int *)malloc(sizeof(int) * size);
list->size = size;
list->top = 0;
inorderTraversal(root, list);
return list->vals[k-1];
}
int main() {
struct TreeNode* root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->val = 2;
struct TreeNode* left = (struct TreeNode *)malloc(sizeof(struct TreeNode));
left->val = 1;
struct TreeNode* right = (struct TreeNode *)malloc(sizeof(struct TreeNode));
right->val = 3;
root->left = left;
root->right = right;
left->left = NULL;
left->right = NULL;
right->left = NULL;
right->right = NULL;
assert(kthSmallest(root, 2) == 2);
return 0;
}