C++建立查找删除节点二叉排序树

58 篇文章 0 订阅

简历方法。二叉树简历。只是小的在根的左边 大的在右边。。

删除 是只写了左右子树都不为空的删除 

删掉当前节点。用一个数据来填补空缺。代码里面看


H

#ifndef H_H
#define H_H
#include <iostream>

struct Node
{
	int num;
	Node*lNext;
	Node*rNext;
};
class BinaryTree
{
public:
	BinaryTree();
	~BinaryTree();	
	void Insert(Node*&p, int m);
	void show(Node*&p);
	Node*Find(int m);
	void Delete(int m);
	Node*pHead;
	
};
#endif //H_H

CPP

#include "h.h"
using namespace std;
BinaryTree::BinaryTree(){}
BinaryTree::~BinaryTree(){}

void BinaryTree::Insert(Node*&p, int m)
{
	if (m < 0)
		return;
	if (p == nullptr)
	{
		p = new Node;
		p->num = m;
		p->lNext = nullptr;
		p->rNext = nullptr;
		return;
	}
	if (m == p->num)return;
	if (m < p->num)
		Insert(p->lNext, m);
	else if (m>p->num)
		Insert(p->rNext, m);

}
void BinaryTree::show(Node*&p)
{
	if (p)
	{
		cout << p->num << endl;
		show(p->lNext);
		show(p->rNext);
	}
}
Node*BinaryTree::Find(int m)
{
	Node*p = pHead;
	while (p)
	{
		if (p->num == m)
			return p;
		if (p->num<m)
		{
			p = p->rNext;
		}
		else
		{
			p = p->lNext;
		}
	}
	return nullptr;
}
void BinaryTree::Delete(int m)
{
	Node*p = Find(m);
	if (!p)
	{
	
		return;
	}
	if (p->lNext&&p->rNext)//先拿个左子树。再一直倒右拐。直到没有右子树了。这个就是拿来替换删掉那个节点的节点了
	{
		Node*temp = p->lNext;
		Node *d = p;

		while (temp->rNext)
		{
			d = temp;
			temp = temp->rNext;
		}
		p->num = temp->num;
		if (d!=p)//这个表明。是倒右拐了的 前驱指向下一个的下一个
		{
			
			Node*t = d->rNext;
			d->rNext = temp->lNext;
			delete t;//处理被过掉那个节点 这个t delete了指向的内存才能重用
			t = nullptr;
			
		}
		else//没有右子树 直接接左边
		{
			Node*t = d->lNext;
			d->lNext = temp->lNext;
			delete t;
			t = nullptr;
			//cout << "temp is " << temp->num << endl;
			
		}
	}
}
int main()
{
	BinaryTree bt;
	//bt.initTree();
	bt.Insert(bt.pHead, 100);
	bt.Insert(bt.pHead, 90);
	bt.Insert(bt.pHead, 110);
	bt.Insert(bt.pHead, 80);
	bt.Insert(bt.pHead, 70);
	bt.Insert(bt.pHead, 65);
	bt.Insert(bt.pHead, 75);
	bt.Insert(bt.pHead, 95);

	bt.show(bt.pHead);
	Node*p = bt.Find(80);
	if (p)
	{
		cout << p->num << " had been found"<<endl << endl;
	}
	else
	{
		cout << "Not Find" << endl;
	}
	bt.Delete(90);试过90 100 都阔以
	bt.show(bt.pHead);
	system("pause");
}
他是你拿后面的节点来填你换的节点这个套路。看图理解理解



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值