二叉树 : 方便查找 搜索速度快 经常需要搜索的数据放入二叉树
#include <iostream>
using namespace std;
typedef char T;
#include <cctype>
#include <iomanip>
class bst //二叉查找树
{
struct Node
{
T data;
Node* L;
Node* R;
//结构也可以写构造函数
Node(const T&d):data(d),L(),R(){} //L R使用零初始化
Node(const T&d,Node *l,Node *r):data(d),L(l),R(r){}
};
typedef Node* tree; //只是为了让后面看起来顺眼点
Node *rp; //根节点指针
int n; //结点个数
/* ------------------二叉树操作函数 (私有) -----------------*/
void insert(tree &t,Node* p) //tree也是Node*
{
if(t == NULL) t=p;
else if(p->data < t->data) insert(t->L,p);
else insert(t->R,p);
}
//查找某个值的位置 返回指向该节点的根节点指针的引用
Node*& 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 travel(const tree t) const
{
if(t != NULL)
{
travel(t->L);
cout << t->data << ' ';
travel(t->R);
}
}
//清空
void clear(tree &t)
{
if(t != NULL)
{
clear(t->L);
clear(t->R);
delete t; t=NULL; //如果要将t设成NULL ,t的类型必须是引用
}
}
int height(tree t) const
{
if(t == NULL ) return 0;
int lh = height(t->L);
int rh = height(t->R);
return ( lh>rh?lh:rh )+1;
}
void print(tree t,int space ,char sign)
{
if(t == NULL) return;
print(t->R,space+1,'/');
cout << setw(space+1) << sign << t->data << endl ; //空格和符号
print(t->L,space+1,'\\');
}
public:
bst():rp(),n(){} //仍然使用零初始化
~bst()
{
clear(rp);
n=0;
}
void insert(const T& d)
{
insert(rp,new Node(d));
++n;
}
// 如何删除一个节点呢?
//1 找到指向这个节点的指针 2 另存一份
//3 左右子树合并 4 指向合并后的子数
//5delete掉节点 6节点个数-1
bool remove(const T &d)
{
Node* &t = find(rp,d);
if( t != NULL )
{
Node *p = t;
if(t->L != NULL) //如果有左子树 则
{
insert(t->R,t->L);
}
t = t->R;
delete p;
--n;
return true;
}
else
return false;
}
//修改:删除旧的 插入新的(二叉树不可直接修改 因为可能这个值不能放在这里)
void update(const T& olddata,const T&newdata)
{
if(remove(olddata)) insert(newdata);
}
void print()
{
print(rp,0,'*');
cout << "------------------" << endl;
}
const T& root() const //返回根节点
{
if(rp == NULL) throw "空";
return rp->data;
}
void travel() const
{
travel(rp);
cout << endl;
}
bool empty() const
{
return n==0;
}
int size() const
{
return n;
}
int height() const
{
return height(rp);
}
};
int main()
{
bst b;
char c;
cin >> ws;
while(isalpha(cin.peek())) //只允许插入字母
{
cin >> c;
b.insert(c);
cin >> ws;
}
cout << b.height() << endl;
b.travel();
// b.remove('c'); //删除一个c
// while(b.remove('b')){} //删除所有的d
//b.travel();
// b.update('g','*'); //g改成* 只改一个
//b.travel();
b.print();
while(!b.empty())
{
b.remove(b.root());
cout << "size:"<< b.size() << endl;
}
}