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

71 lines
1.1 KiB
C
Raw 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 preorderTraversal(treeNode *root) {
if (root) {
printf("%d,", root->val);
preorderTraversal(root->l);
preorderTraversal(root->r);
}
}
int main(void) {
int tmp;
scanf("%d,", &tmp);
treeNode *root = newNode(tmp);
while (scanf("%d,", &tmp) != EOF) {
insertTree(root, tmp);
}
preorderTraversal(root);
freeTree(root);
return 0;
}