要注意的是删除节点的那一部分代码(用前驱或后继替代),结合理论知识来记忆
代码:
#include <stdio.h>
#include <queue>
using namespace std;
struct node{
int data;
node* lchild;
node* rchild;
};
node* root = NULL;
//新建一个节点
node* newNode(int v){
node* Node = new node;
Node->data = v;
Node->lchild = NULL;
Node->rchild = NULL;
return Node;
}
//找到二叉查找树中数据域为x的节点
void search(node* root,int x){
if(root == NULL){
printf("search failed\n");
return;
}
if(x == root->data){
printf("%d\n",root->data);
}
else if(x <root->data){
search(root->lchild,x);
}
else{
search(root->rchild,x);
}
}
//中序遍历
void inorder(node* root){
if(root == NULL){
return;
}
inorder(root->lchild);
printf("%d ",root->data);
inorder(root->rchild);
}
//insert函数将在二叉树中插入一个数据域为x的新节点
void insert(node* &root,int x){
if(root == NULL){
root = newNode(x);//如果节点不存在,新增一个
return;
}
if(x == root->data){//已经存在就返回
return;
}
else if(x <root->data){
insert(root->lchild,x);
}
else{
insert(root->rchild,x);
}
}
//二叉树的建立
node* Creat(int data[],int n){
node* root = NULL;
for(int i = 0;i <n;i++){
insert(root,data[i]);
}
return root;
}
//寻找以root为根节点的树中的最大权值节点
node* findMax(node* root){
while(root->rchild != NULL){
root= root->rchild;//直到没有右孩子
}
printf("最大权值节点的数据为%d\n",root->data);
return root;
}
//寻找以root为根节点的树中的最小权值
node* findMin(node* root){
while(root->lchild != NULL){
root = root->lchild;
}
printf("最小权值节点的数据为%d\n",root->data);
return root;
}
//删除以root为根节点的树中权值为x的节点
void deleteNode(node* &root,int x){
if(root == NULL){
return;
}
if(root->data == x){
if(root->lchild == NULL && root->rchild == NULL){
root = NULL;
}
else if(root->lchild != NULL){//左子树不为空时
node* pre = findMax(root->lchild);
root->data = pre->data;
deleteNode(root->lchild,pre->data);
}
else{//右子树不为空时
node* next = findMin(root->rchild);
root->data = next->data;
deleteNode(root->rchild,next->data);
}
}
else if(root->data>x){//节点数据比x大,前往左子树删除
deleteNode(root->lchild,x);
}
else{//节点数据比x小,前往右子树删除
deleteNode(root->rchild,x);
}
}
int main(){
int data[10] = {1,3,5,7,9,2,4,6,8,10};
node* linshi = Creat(data,10);
findMax(linshi);
findMin(linshi);
printf("中序遍历输出数据为:\n");
inorder(linshi);
deleteNode(linshi,4);
printf("\n删除4后,中序遍历输出数据为:\n");
inorder(linshi);
}