BST是二叉树的一种,其中每个结点的左孩子小于该结点的值,右孩子大于于该结点的值,对该树进行中序遍历可以得到一组有序序列
//二叉搜索树
#include <stdio.h>
typedef struct node {
int data;
struct node *lchild;
struct node *rchild;
} Node;
typedef struct tree {
Node *root;
} Tree;
void insert(Tree *tree, int value) {
Node *node = malloc(sizeof(Node));
node->data = value;
node->lchild = NULL;
node->rchild = NULL;
if (tree->root == NULL) {
tree->root = node;
}
else {
Node *temp = tree->root;
//有问题待查
// while (temp != NULL) {
// if (value > temp->data) {
// temp = temp->rchild;
// }
// if (value < temp->data) {
// temp = temp->lchild;
// }
// }
// temp = node;
while (temp != NULL) {
if (value > temp->data) {
if (temp->rchild == NULL) {
temp->rchild = node;
return;
}
else {
temp = temp->rchild;
}
}
if (value < temp->data) {
if (temp->lchild == NULL) {
temp->lchild = node;
return;
}
else {
temp = temp->lchild;
}
}
}
}
}
void preOrder(Node *node) {
if (node == NULL) {
return;
}
printf("%d\n", node->data);
preOrder(node->lchild);
preOrder(node->rchild);
}
void inOrder(Node *node) {
if (node == NULL) {
return;
}
inOrder(node->lchild);
printf("%d\n", node->data);
inOrder(node->rchild);
}
void postOrder(Node *node) {
if (node == NULL) {
return;
}
postOrder(node->lchild);
postOrder(node->rchild);
printf("%d\n", node->data);
}
int get_height(Node *node) {
if (node == NULL) {
return 0;
}
int left = get_height(node->lchild);
int right = get_height(node->rchild);
if (right > left) {
return right+1;
}
else {
return left +1;
}
}
int get_max(Node *node) {
if (node == NULL) {
return -1;
}
int max = node->data;
int left = get_max(node->lchild);
int right = get_max(node->rchild);
if (max < left) {
max = left;
}
if (max < right) {
max = right;
}
return max;
}
int main() {
int arr[7] = {6, 3, 8, 2, 5, 1, 7};
int i;
Tree T,*tree = malloc(sizeof(Tree));
tree->root = T.root = NULL;
for (i = 0; i < 7; i++) {
insert(tree, arr[i]);
}
inOrder(tree->root);
printf("\nh = %d", get_height(tree->root));
printf("\nMAX = %d\n", get_max(tree->root));
return 0;
}