Skip to content

Commit

Permalink
Kth bst
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Jan 8, 2018
1 parent 383370d commit b55babc
Show file tree
Hide file tree
Showing 2 changed files with 85 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 230_kth_smallest_element_in_a_bst/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test kth_bst.c
83 changes: 83 additions & 0 deletions 230_kth_smallest_element_in_a_bst/kth_bst.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};

static bool traverse(struct TreeNode *node, int *k, int *val)
{
if (node == NULL) {
return false;
}
if (traverse(node->left, k, val)) {
return true;
}
if (--*k == 0) {
*val = node->val;
return true;
}
if (traverse(node->right, k, val)) {
return true;
}
return false;
}

static int kthSmallest(struct TreeNode* root, int k)
{
int value = 0;
traverse(root, &k, &value);
return value;
}

int main(void)
{
#if 1
struct TreeNode root, n10, n11, n20, n21, n22, n23;
root.val = 1;
n10.val = 2;
n11.val = 2;
n20.val = 3;
n21.val = 4;
n22.val = 4;
n23.val = 3;
root.left = &n10;
root.right = &n11;
n10.left = &n20;
n10.right = &n21;
n11.left = &n22;
n11.right = &n23;
n20.left = NULL;
n20.right = NULL;
n21.left = NULL;
n21.right = NULL;
n22.left = NULL;
n22.right = NULL;
n23.left = NULL;
n23.right = NULL;
#else
struct TreeNode root, n10, n11, n21, n22;
root.val = 1;
n10.val = 2;
n11.val = 2;
n21.val = 3;
n22.val = 4;
root.left = &n10;
root.right = &n11;
n10.left = NULL;
n10.right = &n21;
n11.left = &n22;
n11.right = NULL;
n21.left = NULL;
n21.right = NULL;
n22.left = NULL;
n22.right = NULL;
#endif

int k = 1;
printf("%d\n", kthSmallest(&root, k));
return 0;
}

0 comments on commit b55babc

Please sign in to comment.