c++之二叉树的删除

之前已经写了二叉树的创建,插入与旋转,详见https://blog.csdn.net/weixin_42579072/article/details/102616919

pavlNode DeleteNode(pavlNode &root, int key)
{
	if (key < root->key)
	{
		DeleteNode(root->lChild, key);
		if (AvlTreeHeight(root->rChild) - AvlTreeHeight(root->lChild) == 2)
		{//失去平衡,需要旋转
			AvlNode *p = root->rChild;
			if (AvlTreeHeight(p->lChild)>AvlTreeHeight(p->rChild))
				root = RL(root);
			else
				root = RR(root);
		}
	}
	else if (key > root->key)
	{
		DeleteNode(root->rChild, key);
		if (AvlTreeHeight(root->lChild) - AvlTreeHeight(root->rChild) == 2)
		{//失去平衡,需要旋转
			AvlNode *p = root->lChild;
			if (AvlTreeHeight(p->rChild) > AvlTreeHeight(p->lChild))
				root = LR(root);
			else
				root = LL(root);
		}
	}
	else
	{
		if (root->lChild&&root->rChild)//左右子树都存在
		{
			if (AvlTreeHeight(root->lChild) > AvlTreeHeight(root->rChild))
			{
				AvlNode *p = TreeNodePre(root->lChild);
				root->key = p->key;
				DeleteNode(root->lChild, p->key);
			}
			else
			{
				AvlNode *p = TreeNodePost(root->rChild);
				root->key = p->key;
				DeleteNode(root->rChild, p->key);
			}
		}
		else
		{
			if (root->lChild)//只存在左子树
			{
				root->key = root->lChild->key;
				root->lChild = nullptr;
			}
			else if (root->rChild)//只存在右子树
			{
				root->key = root->rChild->key;
				root->rChild = nullptr;
			}
			else //叶子结点
				root = nullptr;
		}
	}
	return root;
}

别忘了在MyAVL.h中加入该函数声明。
main.cpp如下:

#include"MyAVL.h"
#include<iostream>
#define len 10
using namespace std;

int main()
{
	int a[len] = { 3, 2, 1, 4, 5, 6, 7, 10, 9, 8 };
	cout << "待插入元素为:";
	for (int i = 0; i < len; i++)
	{
		cout << a[i] << " ";
	}
	cout << endl;

	pavlNode root = NULL;
	for (int i = 0; i < len; i++)
	{
		root = InsertNode(root,a[i]);
		if (NULL == root)
			cout << "插入" << a[i] << "失败" << endl;
	}
	cout << "中序遍历:";
	InOrder(root);
	cout << endl;
	cout << "前序遍历:";
	PreOrder(root);
	cout << endl;

	cout << "删除指定节点后:"<<endl;
	root = DeleteNode(root, 7);
	cout << "中序遍历:";
	InOrder(root);
	cout << endl;
	cout << "前序遍历:";
	PreOrder(root);
	cout << endl;
	TreeDestroy(root);

	system("pause");
	return 0;

}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值