C++ 数据结构-------二叉树实现
来源:互联网 发布:php排序算法 编辑:程序博客网 时间:2024/04/29 03:33
最近写了一个简单的二叉树,仅供查考,代码如下:
#include <iostream>
using namespace std;
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):data(d),L(l),R(r){}
};
typedef Node* tree;
Node* rp;
int n;
public:
bst():rp(),n(){}
~bst()
{
clear();
}
void clear()
{
clear(rp);
n = 0;
}
void insert(const T& d)
{
insert(rp,new Node(d));
++n;
}
tree& find(const T& d)
{
return find(rp,d);
}
void travel()const
{
travel(rp);
cout << endl;
}
bool empty()const
{
return rp == NULL;
}
int size()const
{
return n;
}
bool remove(const T& d) //删除树中指定数值的节点
{
tree& t = find(d);
if(t == NULL) return false;
Node* p = t;
if(t->L != NULL) insert(t->R,t->L);
t = t->R;
delete p;
--n;
return true;
}
const T& root()const
{
if(rp == NULL) throw "空";
return rp->data;
}
void update(const T& olddata,const T& newdata) //修改节点的数据
{
if(remove(olddata))
insert(newdata);
}
private:
static 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);
}
static tree& find(tree& t,const T& d) //返回已d为根节点的子树的根指针
{
if(t == NULL) return t; //没找到
else if(t->data == d) return t; //找到了
else if(d < t->data)
return find(t->L,d);
else
return find(t->R,d);
}
static void travel(tree t) //遍历
{
if(t != NULL)
{
travel(t->L);
cout << t->data << ' ';
travel(t->R);
}
}
static void clear(tree& t) //清空
{
if(t != NULL)
{
clear(t->L);
clear(t->R);
delete t;
t = NULL;
}
}
static int high(tree t)
{
if(t == NULL) return 0;
int lh = high(t->L);
int rh = high(t->R);
return 1+(lh>rh?lh:rh);
}
};
int main()
{
bst b;
b.insert('k');
b.insert('s');
b.insert('f');
b.insert('t');
b.insert('a');
b.insert('m');
b.insert('x');
b.insert('e');
b.travel();
b.remove('k');
b.travel();
b.update('x','*');
b.travel();
while(!b.empty())
b.remove(b.root());
cout << "size: " << b.size() << endl;
b.travel();
return 0;
}
- 数据结构的C实现_二叉树
- (C语言)二叉树实现(数据结构十三)
- C 实现数据结构二叉查找树
- [数据结构]C语言二叉树的实现
- 数据结构 二叉树的实现 c语言版
- c语言实现二叉树数据结构
- 数据结构(C实现)------- 遍历二叉树
- C语言二叉树的数据结构实现
- 数据结构:二叉树的实现(C++)
- 数据结构之---二叉树C实现
- 数据结构:二叉查找树(C语言实现)
- 【数据结构】数据结构C语言的实现(简单二叉树)
- 数据结构(C++)--二叉树
- 二叉树(数据结构 c++)
- 【数据结构】二叉树(c++)
- 数据结构-二叉树实现
- 数据结构 二叉树实现
- 二叉树数据结构实现
- HDU - 3549 Flow Problem
- 解决:在使用JSONP跨域请求时.AJAX的dataFilter获取返回数据出现undifined
- Php的mail()函数的使用
- 关于XML的tips
- Recurrent Neural Networks with Word Embeddings¶
- C++ 数据结构-------二叉树实现
- 书评之《彷徨之刃》
- 封装mvc框架【三】配置类
- 继承SwipeRefreshLayout实现上拉刷新
- CSS盒子模型
- XML解析
- Python初学 寻找第n个默尼森数
- [读书笔记]布局的屏幕适配常用方法
- 深入浅出MFC:MFC的MessageMaping