二叉排序树的各项操作
#include <stdio.h> #include <stdlib.h> #define MAX 20 typedef int datatype; typedef struct bi_search_tree { datatype key; struct bi_search_tree *left,*right; }*bst_tree; /*插入操作,value是待插入的值*/ bst_tree bst_insert(bst_tree root, datatype value) { bst_tree parent, node, child; /*树为空,创建根节点*/ if(root == NULL) { root = (bst_tree )malloc(sizeof(bst_tree)); root->key = value; root->left = NULL; root->right = NULL; return root; } parent = root; /*记录下根节点的位置*/ node = root; while(node != NULL) { /*待插入数据已经存在,则返回*/ if(node->key == value) return root; else { parent = node; /*若小于节点的值,则查看节点的左孩子,否则,查看右孩子*/ if(node->key < value) node = node->right; else node = node->left; } } child = (bst_tree )malloc(sizeof(bst_tree)); child->key = value; child->left = NULL; child->right = NULL; if(value > parent->key) parent->right = child; else parent->left = child; return root; } /*查找,找到返回1,否则,返回0*/ int bst_search(bst_tree root, datatype value) { bst_tree p; p = root; if(p == NULL) return 0; if(p->key == value) return 1; else if(p->key > value) return bst_search(p->left, value); else return bst_search(p->right, value); } /*删除节点值为value的节点*/ int bst_delete(bst_tree root, datatype value) { bst_tree p, pre=NULL, mid; p = root; if(root == NULL) return 0; /*找到该节点*/ while((p != NULL) && (p->key != value)) { pre = p; if(p->key < value) { p = p->right; } else p = p->left; } if(p == NULL) return 0; /*至少有一个子节点为空*/ if( (p->left == NULL) || (p->right == NULL) ) { if( pre->left == p ) { pre->left = ( (p->left == NULL) ? p->right : p->left ); } else pre->right = ( (p->left == NULL) ? p->right : p->left ); free(p); /*释放节点*/ } else { /*删除的节点有2个子女*/ mid = p->right; pre = p; /*寻找中序的第一个节点*/ while(mid->left != NULL) { pre = mid; mid = mid->left; } /*移花接木,直接赋值,避免交换节点*/ p->key = mid->key; /*将mid节点的子节点作为pre的子节点,并将mid所指向的节点删除*/ if(pre->right == mid) pre->right = mid->right; else pre->left = mid->right; free(mid); } return 1; } /*中序输出bst树*/ void bst_print(bst_tree root) { if(root == NULL) return; bst_print(root->left); printf(" %d ", root->key); bst_print(root->right); } int main() { /*插入操作,value是待插入的值*/ bst_tree bst_insert(bst_tree root, datatype value); /*查找,找到返回1,否则,返回0*/ int bst_search(bst_tree root, datatype value); /*删除节点值为value的节点,成功返回1,否则,返回0*/ int bst_delete(bst_tree root, datatype value); /*中序输出bst树*/ void bst_print(bst_tree root); bst_tree root=NULL; int a[MAX]; int i=0; int length; printf("输入二叉排序树的记录个数:\n"); scanf("%d",&length); printf("输入要创建的二叉排序树的各个记录:\n"); for(i=0; i<length; i++) { scanf("%d",&a[i]); root = bst_insert(root, a[i]); } bst_delete(root, 5); bst_print(root); printf("\n%d %s\n", root->key, bst_search(root, 10) ? "yes":"no"); return 0; }用于存储代码,同时希望对广大博友有用