BUPT-homework/semester3/pset2/2-1-Binary-Search-Tree.c

89 lines
1.4 KiB
C
Raw Permalink Normal View History

2022-10-14 18:47:09 +08:00
#include <stdio.h>
#include <stdlib.h>
typedef struct treeNode {
int val;
struct treeNode *l;
struct treeNode *r;
} treeNode;
treeNode *newNode(int val) {
treeNode *root = malloc(sizeof(treeNode));
root->val = val;
root->l = NULL;
root->r = NULL;
return root;
}
void insertTree(treeNode *root, int val) {
// Only insert at leaf.
treeNode *par;
int isL;
treeNode *ptr = root;
while (ptr != NULL) {
par = ptr;
if (ptr->val < val) {
ptr = ptr->r;
isL = 0;
} else {
ptr = ptr->l;
isL = 1;
}
}
if (isL) {
par->l = newNode(val);
} else {
par->r = newNode(val);
}
}
void freeTree(treeNode *root) {
if (root) {
freeTree(root->l);
freeTree(root->r);
free(root);
}
}
void printLevel(treeNode *root, int level, int *hasOutput) {
if (root == NULL) {
return;
}
if (level == 1) {
*hasOutput = 1;
printf("%d,", root->val);
} else {
printLevel(root->l, level - 1, hasOutput);
printLevel(root->r, level - 1, hasOutput);
}
}
int main(void) {
int size;
int level;
scanf("%d", &size);
int tmp;
scanf("%d,", &tmp);
treeNode *root = newNode(tmp);
for (int i = 1; i < size; i++) {
scanf("%d,", &tmp);
insertTree(root, tmp);
}
scanf("%d", &level);
int *hasOutput = malloc(sizeof(int));
*hasOutput = 0;
printLevel(root, level, hasOutput);
if (*hasOutput == 0) {
printf("-1");
}
free(hasOutput);
freeTree(root);
return 0;
}