CPP二叉树

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
/*
@@二叉树
@@来自达内视频,版权归达内所有。
@@二叉树,一是:定义,
@@····二是:递归!
@@好处:便于查找,搜索速度很快,每次除以2;
@@ 搜索一次,数据数量排除一半
*/
typedef char T;
class bst{
struct Node
{
T data;
Node *L;//左子树
Node *R;//右字数
Node(const T&d) :data(d), L(), R(){}
Node(const T&d, Node *l, Node *r) :L(l), R(r), data(d){}


~Node(){}
};
typedef Node* tree;
Node* rootptr;
int n;
public:
bst() :rootptr(NULL), n(0){}
/*
简化函数
*/
//插入
void Insert(const T&d)
{
insert(rootptr, new Node(d));
++n;
}
//查找
tree& Find(const T&d)
{
return find(rootptr, d);
}
//遍历
void Show()const
{
showtree(rootptr);
cout << endl;
}
//清空
void clear()
{
cleartree(rootptr);
}
/*
@@取得根节点数据
*/
const T& root()const
{
if (!rootptr)throw "空";
return rootptr->data;
}
/*
@@跟新某个节点的数据
*/
void updata(const T&olddata, const T&newdata)
{
if(remove(olddata))
Insert(newdata);
}
//析构
~bst()
{
clear();
}
///
/
/*
@@在一棵树里面插入一个节点,tree &t更改数据
*/
void insert(tree &t, Node* p)//
{
if (t == NULL)
t = p;
else if (p->data < t->data)
insert(t->L, p);//左子树插入数据
else
insert(t->R, p);//右子树插入数据
}
/*
@@查找节点数
@@返回以d为根节点的子树的根指针
@@返回值,函数的参数等很知道品味!
*/
tree &find(tree &t, const T&d)
{
if (t == NULL) return t;
else if (d == t->data)
{
return t;
}
else if (d < t->data)
return find(t->L, d);
else
return find(t->R, d);
}


/*
@@遍历一棵树
@@以中序为例
*/
void showtree(tree t)const
{
if (t != NULL)
{
showtree(t->L);//左
cout << t->data << ",";//根
showtree(t->R);//右
}
}
/*
@@清空
*/
void cleartree(tree &t)
{
if (t != NULL)
{
cleartree(t->L);
cleartree(t->R);
delete t;//最好最后释放根节点
t = NULL;//根节点设为空,需要把参数设置为引用
}
}
/*
@@统计树有多高,多少层
*/
int hightree(tree t)
{
if (t == NULL) return 0;
int lh = hightree(t->L);
int rh = hightree(t->R);
return max(lh, rh) + 1;//左右最高+1;
}
/*
@@是否为空
*/
bool isempty()const
{
return rootptr == NULL;
}
/*
@@大小
*/
int size()const
{
return n;
}
/*
@@删除
@@将左子树插入到右子树
*/
bool remove(const T&d)
{
tree &t = find(rootptr,d);
if (t == NULL) return false;
Node *p = t;
if (t->L!=NULL)//有左子树
insert(t->R, t->L);//将左子树插入到右子树
t = t->R;
delete p;
--n;//节点数减去1
return true;
}
};
**测试**/
void main()
{
bst b;
b.Insert('k');
b.Insert('a');
b.Insert('g');
b.Insert('h');
b.Insert('s');
b.Insert('3');
b.Insert('i');
b.Insert('o');
b.Show();
b.remove('i');
b.Show();
b.updata('3', '9');
cout << b.size() << endl;
cout <<b.Find('s')->data<<endl;
b.Show();
while (!b.isempty())
{
b.remove(b.root());
b.Show();
}
cout << "size:" << b.size() << endl;
b.Show();
system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值