linux下练习 c++ 有序二叉树
来源:互联网 发布:还珠格格燕子复仇知画 编辑:程序博客网 时间:2024/06/08 16:20
#include <iostream>using namespace std;typedef int T;class bst//有序的二叉查找树{struct Node{T data;Node * L;Node * R;Node(const T&d):data(d),L(),R(){}//将L或R初始化为0Node(const T&d,Node * l,Node * r):data(d),L(l),R(r){}};typedef Node* tree;Node * root;//根结点int n;//记录节点个数public:bst():root(),n(){}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);}void insert(const T& d){insert(root,new Node(d));++n;}tree& find(tree& t,const T& d)//查找,&代表指针本身{if(t==NULL) return t;//返回tree类型的else if(d==t->data) return t;else if(d<t->data) return find(t->L,d);else return find(t->R,d);}tree& find(const T& d){return find(root,d);}void travel(tree t) const//遍历{if(t!=NULL){travel(t->L);cout<<t->data<<" ";travel(t->R);}}void travel(){travel(root);cout<<endl;}bool empty()const//是否为空{return root==NULL;}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;//t指向右子树delete p;//删除结点空间--n;return true;}int size()const {return n;}void update(const T& olddata,const T& newdata)//修改数据{if(remove(olddata)) insert(newdata);//删除旧的,插入新的}const T& rdata()const{if(!root) throw "空";return root->data;}void clear(tree& t)//清空,释放内存{if(t!=NULL){clear(t->L);clear(t->R);delete t;t=NULL;cout<<"内存释放完成!\n";n=0;}}void clear(){clear(root);}int height(tree t)//高度{if(t==NULL) return 0;int lh=height(t->L);int rh=height(t->R);return 1+(lh>rh?lh:rh);}int height(){return height(root);}};int main(){bst b;b.insert(4);//插入b.insert(5);b.insert(-23);b.insert(24);b.insert(77);b.insert(20);b.update(20,28);//20修改为28b.remove(4);//删除4的节点b.travel();//遍历一下cout<<b.rdata()<<endl;return 0;}
g++ -o tree.out tree.cpp
./tree.out
- linux下练习 c++ 有序二叉树
- 【l练习代码】有序二叉树的操作
- 平衡二叉有序树
- [每日练习]C编程实现二叉树
- 自我练习8 ----- 把一个有序整数数组放到二叉树中
- 二叉树定义--有序树
- 广度遍历有序二叉树
- 有序二叉树的算法
- 有序二叉树的操作
- 有序二叉树的实现
- 二叉树转为有序列表
- 有序二叉树的实现
- linux下的二叉树
- C/C++基本数据结构:有序二叉树的基本概念和实现
- C语言数据结构——数据结构有序二叉树的函数实现
- 有序二叉树转为有序双向链表
- Python 二叉树练习
- 练习--链式二叉树
- 图形学一系列网站【包括各牛校的教学、杂志和会议等】
- regsvr32注册与反注册 ActiveX EXE ocx dll
- remote和local 的区别
- vs2010版本程序能不能在vs2008上运行
- 左右连接
- linux下练习 c++ 有序二叉树
- 设计模式 Facade模式
- 锦州小狠嗑
- hdu 3718 Similarity(费用流应用)
- 在线安装ADT总是出现以下错误
- 【Tiny6410 And Linux】—(6.2)—LCD 驱动测试程序(BMP 显示位图)——代码
- Rational Rose 2003 下载及破解方法
- oracle的rowid和rownumber
- LCD 调屏几种现象及原因