struct TreeNode{
int data;
TreeNode* lchild, *rchild;
};
TreeNode * search(TreeNode * &root, int key){
TreeNode *p,*s;
s=p = root;
while (p){
s = p;
cout << "查找过程遇到的节点值为:" << p->data << endl;
if (p->data == key)
return NULL;
key > p->data ? p = p->rchild : p = p->lchild;
}
return s;
}
bool insert(TreeNode* &root, int key){
TreeNode *p,*s;
p = new TreeNode();
p->data = key;
p->lchild = NULL; p->rchild = NULL;
s = search(root, key);
if ( s == NULL&&root!=NULL){
delete p;
return false;
}
else{
if (root == NULL){
cout << "根节点建立,值为:" << p->data << endl;
root = p;
}
else{
cout << "插入的节点的根节点为:" << s->data << endl;
key > s->data ? s->rchild=p : s->lchild=p;
}
return true;
}
}
void Show(TreeNode * root){
//cout << "下面输出二叉树的前序遍历信息:" << endl;
TreeNode*p = root;
if (p)
{
Show(p->lchild);
cout << p->data << endl;
Show(p->rchild);
}
}
void del_node(TreeNode * &root, int key){
TreeNode* p, *parent, *s;
p = root;
parent = s = NULL;
if (p == NULL){
return;
}
if (p->data == key){
//需删除的节点无左右孩子节点
if (p->lchild == NULL&&p->rchild == NULL){
root = NULL;
delete p;
}
//需删除的节点有左孩子无右孩子
else if (p->rchild == NULL){
root = p->lchild;
delete p;
}
//需删除的节点无左孩子有右孩子
else if (p->lchild == NULL){
root = p->rchild;
delete p;
}
//需删除的节点有左右孩子
else{
//找到需删除节点右孩子的最左孩子节点
//使找到的节点与需要删除的节点做替换
s = p->rchild;
//需删除节点右孩子的最左孩子节点为空,
if (s->lchild == NULL){
s->lchild = p->lchild;
}
else{
while (s->lchild){
parent = s;
s = s->lchild;
}
parent->lchild = s->rchild;
//把需要删除的节点的孩子节点全部转移给找到的节点
s->lchild = p->lchild;
s->rchild = p->rchild;
}
//一定不要忽略这步,否则二叉链表树会断掉
//此步即:把需要删除的节点的孩子节点全部转移给找到的节点后,
//再交换二者位置,完成链表的链接
root = s;
//链接完成后再删除
delete p;
}
}
else if (key > p->data){
del_node(p->rchild, key);
}
else if (key < p->data){
del_node(p->lchild, key);
}
}
int main(){
TreeNode* root=NULL;
int x;
cout << "输入节点信息:" << endl;
cin >> x;
while (x != 0){
if (insert(root, x) != false){
cout << "输入节点信息:" << endl;
cin >> x;
}
else
break;
}
//中序遍历二叉线索树得到的即是顺序表
cout << "下面输出二叉树的中序遍历信息:" << endl;
Show(root);
cout << "输入想删除的节点为:" << endl;
cin >> x;
del_node(root, x);
cout << "删除后的二叉树中序遍历信息:" << endl;
Show(root);
}
简易版二叉查找树(查找,插入,遍历,删除)
最新推荐文章于 2024-04-27 22:06:31 发布