binary search tree

来源:互联网 发布:windows测试udp端口 编辑:程序博客网 时间:2024/06/07 00:48
#include <stdio.h>#include <stdlib.h>typedef struct tnode {int key;struct tnode *parant;struct tnode *left;struct tnode *right;} TNODE;typedef TNODE *TREE;void InorderTreeWalk(TREE t){if (t) {InorderTreeWalk(t->left);printf("%d\t", t->key);InorderTreeWalk(t->right);}}TNODE *TreeMin(TREE t){// if (t == NULL || t->left == NULL)// return t;// else// return TreeMin(t->left);if (t == NULL)return t;while (t->left) {t = t->left;}return t;}TNODE *TreeMax(TREE t){if (t == NULL)return t;while (t->right) {t = t->right;}return t;}// 查找x的前驱TNODE *TreePredecessor(TREE t, TNODE *x){if (x->left != NULL) {return TreeMax(x->left);} else {TNODE *y = x->parant;while (y != NULL && x == y->left) { x = y;               y = y->parant;}return y;}}// 查找x的后驱TNODE *TreeSuccessor(TREE t, TNODE *x){if (x->right != NULL) {return TreeMin(x->right);} else {TNODE *y = x->parant;while (y != NULL && x == y->right) { // x向上查找 x = y;               y = y->parant;}return y;}}TNODE *TreeSearch(TREE t, int key){// if (t == NULL || key == t->key) // 注意结束条件// return t;// if (key < t->key)// return TreeSearch(t->left, key);// else // key > t->key// return TreeSearch(t->right, key);while (t != NULL && key != t->key) {if (key < t->key)t = t->left;elset = t->right;}return t;}TREE TreeInsert(TREE t, TNODE *z){TNODE *x = t;TNODE *y = NULL;while (x != NULL) {y = x;if (z->key < x->key)x = x->left;elsex = x->right;}z->parant = y;if (y == NULL)t = z; // tree t was emptyelse if (z->key < y->key)y->left = z; // 左孩子elsey->right = z; // 右孩子return t;}TREE Transplant(TREE t, TNODE *u, TNODE *v){if (u->parant == NULL)t = v;else if (u == u->parant->left)u->parant->left = v;elseu->parant->right = v;if (v != NULL)v->parant = u->parant;return t;}TREE TreeDelete(TREE t, TNODE *z){if (z->left == NULL)t = Transplant(t, z, z->right);else if (z->right == NULL)t = Transplant(t, z, z->left);else {TNODE *y = TreeMin(z->right);if (y->parant != z) {t = Transplant(t, y, y->right);y->right = z->right;y->right->parant = y;}t = Transplant(t, z, y);y->left = z->left;y->left->parant = y;free(z);}return t;}int main(){int arr[] = {19, 8, 27, 3, 13, 23, 45, 1, 11, 14, 20};int len = sizeof(arr) / sizeof(arr[0]);TREE t = NULL;for (int i = 0; i < len; i++) {TNODE *p = (TNODE *)malloc(sizeof(TNODE));if (!p) {printf("p malloc error\n");return -1;}p->key = arr[i];p->parant = p->left = p->right = NULL;t = TreeInsert(t, p);}InorderTreeWalk(t);printf("\n");TNODE *x = TreePredecessor(t, TreeSearch(t, 23));TNODE *y = TreeSuccessor(t, TreeSearch(t, 8));printf("23的前驱是:%d\n8的后继是:%d\n", x->key, y->key);for (int i = 0; i < len; i++) {t = TreeDelete(t, TreeSearch(t, arr[i]));InorderTreeWalk(t);printf("\n");}system("pause");return 0;}

0 0