数据结构系列18 - 二叉排序树 - 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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*************************************************************************
* File Name: binarySearchTree.c
* Author: TyrantLucifer
* E-mail: TyrantLucifer@gmail.com
* Blog: https://tyrantlucifer.com
* Created Time: Wed 14 Jul 2021 11:11:49 PM CST
************************************************************************/
#include <stdio.h>
#include <stdlib.h>

typedef struct TreeNode {
int data;
struct TreeNode* lchild;
struct TreeNode* rchild;
}TreeNode;

TreeNode* bstSearch(TreeNode* T, int data) {
if (T) {
if (T -> data == data) {
return T;
}
else if (data < T -> data) {
return bstSearch(T -> lchild, data);
}
else {
return bstSearch(T -> rchild, data);
}
}
else {
return NULL;
}
}

void bstInsert(TreeNode** T, int data) {
if (*T == NULL) {
*T = (TreeNode*)malloc(sizeof(TreeNode));
(*T) -> data = data;
(*T) -> lchild = NULL;
(*T) -> rchild = NULL;
}
else if (data == (*T) -> data) {
return;
}
else if (data < (*T) -> data) {
bstInsert(&((*T) -> lchild), data);
}
else {
bstInsert(&((*T) -> rchild), data);
}
}

void preOrder(TreeNode* T) {
if (T) {
printf("%d ", T -> data);
preOrder(T -> lchild);
preOrder(T -> rchild);
}
}

int main() {
TreeNode* T = NULL;
int nums[6] = {8, 6, 10, 9, 11, 23};
for (int i = 0; i < 6; i++) {
bstInsert(&T, nums[i]);
}
preOrder(T);
printf("\n");
}