二叉树查找树...

15 篇文章 0 订阅
#include <iostream>
#include <Stack>
#include <Queue>
#include <cstdio>
using namespace std;
//R 大 L 小 
struct Node{
Node* L;
Node* R;
Node* root;
int data;
Node(int d=0):data(d),L(),R(){}
};
class bst{
int n;
public:
Node* head;
bst():head(),n(){}
~bst(){}
void clear(){
n=0;
stack<Node* > m;
if(head==NULL)
return;
m.push(head);
Node * tp;
while(!m.empty())
{
tp=m.top();
if(tp->R!=NULL)
m.push(tp->R);
if(tp->L!=NULL)
m.push(tp->L);
m.pop();
delete tp;
}
}
bool empty ()const {
return n==0;
}
int size() const {
return n;
}
bool remove(const int d)
{
Node* rechild=const_cast<Node *>(find(d));
if(rechild==NULL)
return false;
else
{
if(rechild->L&&rechild->R)
{
Node* min=rechild->R;
while(min->L!=NULL)
min=min->L;
rechild->data=min->data;
if(min->R!=NULL)
{
min->data=min->R->data;
Node* temp=min->R;
min->R=NULL;
delete temp;
}
else
{
min->root->L=NULL;
delete min;
}
}
else if(rechild->L)
{
if(rechild->root->L=rechild)
{
rechild->root->L=rechild->L;
}
else
{
rechild->root->R=rechild->L;
}
delete rechild;
}
else if(rechild->R)
{
if(rechild->root->L=rechild)
{
rechild->root->L=rechild->R;
}
else
{
rechild->root->R=rechild->R;
}
delete rechild;
}
else
{
if(rechild->root->L=rechild)
{
rechild->root->L=NULL;
}
else
{
rechild->root->R=NULL;
}
delete rechild;
}
}
--n;
return true;
}
void insert(const int d){
//R 大 L 小 
Node* p=new Node(d);
if(head==NULL)
{
head=p;
}
else
{
Node* tp=head;
bool t=true;
while(t)
{
if(tp->data<d)
{
if(tp->R==NULL)
{
tp->R=p;
p->root=tp;
t=false;
}
else
{

tp=tp->R;
}
}
else
{
if(tp->L==NULL)
{
tp->L=p;
p->root=tp;
t=false;
}
else
{
tp=tp->L;
}
}
}
}
++n;
}
const Node* find(const int d){
if(head==NULL)
return NULL;
Node* t = head;
while(1)
{
if(t->data==d)
{
return t;
}
else if(t->data<d)
{
t=t->R;
}
else
{
t=t->L;
}
if(t==NULL)
return NULL;
}
}
void travel(int p=1){
if(p==1)
{
stack<Node*> m;
Node *temp=head;
if(head==NULL)
return ;
while(temp!=NULL||!m.empty())
{
while(temp!=NULL)
{
printf("%d ",temp->data);
m.push(temp);
temp=temp->R;
}
if(!m.empty())
{
temp=m.top();
m.pop();
temp=temp->L;
}
}
}
else if(p==2)
{
queue<Node*> m;
Node *temp=head;
if(head!=NULL)
{
m.push(head);
}
while(!m.empty())
{
temp=m.front();
m.pop();
printf("%d ",temp->data);
if(temp->L!=NULL)
{
m.push(temp->L);
}
if(temp->R!=NULL)
{
m.push(temp->R);
}
}
printf("\n");
}
else if(p==3)
{
look(head);
}

}
int high()
{
if(head==NULL)
{
return 0;
}
else
{
;
}
}
void look(Node* root)
{
if(!root)return;
Node* nodex = root;
while(nodex)
{
if(nodex->L)
look(nodex->L);
printf("%d ",nodex->data);
nodex = nodex->R;
}
}
};
int main(int argc, char *argv[])
{
bst b;
b.insert(11);
b.insert(3);
b.insert(33);
b.insert(20);
b.insert(12);
b.insert(2);
b.travel(3);
return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值