二叉排序树的结构体
struct data{ int sum; struct data *left ,*right; };
二叉排序树的插入
void intree(struct data **tree,int a){ //二叉排序树的插入(非递归) struct data *tail = *tree; struct data *news = (struct data *)malloc(sizeof(struct data)); news->sum = a; news->left = news->right = NULL; if(tail == NULL){ (tail) = news; } while((tail) != NULL) { if ((tail)->sum > a) { if ((tail)->left == NULL) { (tail)->left = news; break; } else { tail= tail->left; } }else if(tail->sum < a) { if (tail->right == NULL) { tail->right = news; break; } else { tail= tail->right; } } if(tail->sum == a){ //当树内已经存在插入的数据时 不进行操作 break; } } }
二叉排序树找最小值
struct data *FindMin( struct data* BST ){ if(BST == NULL) return NULL; else if(BST->left == NULL) return BST; else return FindMin(BST->left); }
二叉排序树的删除
struct data* Delete( struct data* BST, int X ){ struct data* temp; if(BST == NULL ) { return NULL; } else{ if(BST->sum > X){ BST->left = Delete(BST->left,X); }else if(BST->sum < X){ BST->right = Delete(BST->right,X); } else if(BST->sum == X){ if(BST->left && BST->right){ temp = FindMin(BST->right); BST->sum = temp->sum; BST->right = Delete(BST->right,BST->sum); } else{ temp = BST; if(!BST->left ){ BST = BST->right; } else { BST = BST->left; } free(temp); } } return BST; } }
二叉排序树查找父结点
struct data * find_father(struct data *tree, int x){ // 线索二叉树寻找结点的父亲结点 中序遍历 struct data *p = NULL; //指向查找结点的前一个 if(tree == NULL) return NULL; if(tree) { while (tree) { if (tree->sum == x) break; //查到的出口 if (tree->sum > x) { p = tree; tree = tree->left; } else if (tree->sum < x) { p = tree; tree = tree->right; } else { break; } } } return p; }
二叉排序树的镜像
/* struct data * mirror_tree(struct data *tree){ //二叉树的镜像调换 (带返回值) if(tree == NULL) return NULL; if(tree){ if(!tree->right && !tree->left) return NULL; //左右子树都为空的情况下,直接返回空 struct data *temp; //临时储存左右子树的结点 temp = tree->right; tree->right = tree->left; tree->left = temp; mirror_tree(tree->left); //继续将左右子树结点下面的子树进行镜像调换 mirror_tree(tree->right); } return tree; } */ void mirror_tree(struct data* *tree) { //不带返回值,传地址 镜像二叉树 if ((*tree) == NULL) return; if (*tree) { if (!(*tree)->left && !(*tree)->right) return; struct data *temp = (*tree)->right; (*tree)->right = (*tree)->left; (*tree)->left = temp; mirror_tree(&(*tree)->left); mirror_tree(&(*tree)->right); } }
统计二叉排序树内结点数
int count_tree(struct data *tree){ //统计二叉树内的结点数 if(tree == NULL) return 0; else return count_tree(tree->right) + count_tree(tree->left) + 1; //否则结点个数为左子树的结点个数+右子树的结点个数+1 }