forked from begeekmyfriend/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Signed-off-by: begeekmyfriend <[email protected]>
- Loading branch information
1 parent
383370d
commit b55babc
Showing
2 changed files
with
85 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
all: | ||
gcc -O2 -o test kth_bst.c |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |