#include<stdio.h>3d
#include<stdlib.h>code
typedef int elementType;递归
typedef struct Search_Tree {element
elementType data; struct Search_Tree *left; struct Search_Tree *right;
}Search, *Tree;get
//递归的插入法,很容易理解io
void insert(Tree *head, int x) {遍历
if (*head == NULL) { (*head) = (Tree)malloc(sizeof(Search)); printf("插入成功\n"); (*head)->data = x; (*head)->left = (*head)->right = NULL; } else if (x < (*head)->data) { insert(&(*head)->left, x); } else { insert(&(*head)->right, x); }
} //先序遍历数据
void preOrder(Tree head) {di
if (head == NULL) return; else { printf("%3d", head->data); preOrder(head->left); preOrder(head->right); }
}while
//中序遍历
void middleOrder(Tree head) {
if (head == NULL) { return; } else { middleOrder(head->left); printf("%3d", head->data); middleOrder(head->right); }
}
//后序遍历
void afterOrder(Tree head) {
if (head == NULL) { return; } else { afterOrder(head->left); afterOrder(head->right); printf("%3d", head->data); }
}
//查找元素,递归查找,属于尾递归,能够改成非递归的方式
Tree find(Tree head, int x) {
if (!head || head->data == x) return head; else if (head->data > x) { return find(head->left, x); } else { return find(head->right, x); }
}
//找最小值
Tree min(Tree head) {
//请注意这个地方的处理,老是存储空以前的一个节点,就是最小值节点 Tree temp = head; while (head != NULL) { temp = head; head = head->left; } return temp;
}
//找最大值
Tree max(Tree head) {
Tree temp = head; while (head != NULL) { temp = head; head = head->right; } return temp;
}
//删除元素
Tree delete_tree(Tree head, int x) {
Tree temp; if (head == NULL) printf("要删除的元素没有找到"); else if (x < head->data)//若是要删除的元素小于当前节点的数据,就到左子树去删 head->left = delete_tree(head->left, x); else if (x > head->data) { //若是要删除的元素大于当前节点的数据,就到右子树去删 int te = head->data; printf("%d\n", te); head->right = delete_tree(head->right, x); } else { //若是找到了的话, int t1 = head->data; printf("%d\n", t1); if (head->left&&head->right) {//判断左右子树非空 temp = min(head->right); //咱们使用又子树的最小值来填充该节点 head->data = temp->data; head->right = delete_tree(head->right, head->data); } else { temp = head; if (!head->left) head = head->right; else if (!head->right) head = head->left; free(temp); } } return head;
}
//非递归查找
Tree find1(Tree head, int x) {
while (head != NULL) { if (head->data == x) return head; else if (head->data > x) head = head->left; else head = head->right; } return head;
}
int main() {
int i; int a[] = {5,3,2,4,8,7,9}; int length = sizeof(a) / sizeof(a[0]); Tree p = NULL; for (i = 0; i < length; i++) { insert(&p, a[i]); } //次地方返回的是头结点,我没有接收 delete_tree(p, 8); preOrder(p); printf("\n"); middleOrder(p); printf("\n"); afterOrder(p); printf("\n"); Tree temp = find(p, 3); printf("%d\n", temp->data); Tree temp1 = min(p); printf("min=%d\n", temp1->data); Tree temp2 = max(p); printf("max=%d\n", temp2->data); getchar(); return 0;
}