顺序二叉树:
#include <bits/stdc++.h>
using namespace std;
typedef struct My1{
int data;
struct My1 *l;
struct My1 *r;
}Node;
二叉顺序树查找
Node *MySearch(Node* t,int x)
{
if (!t)
return NULL;
else if (x==t->data)
return t;
else if (x<t->data)
return MySearch(t->l,x);
else
return MySearch(t->r,x);
}
Node *MySearch1(Node* t,int x)
{
Node *p=t;
while(p)
{
if (x==p->data)
return p;
else if (x<p->data)
p=p->l;
else
p=p->r;
}
return NULL;
}
二叉顺序树插入
Node *MyInsert(Node* &t,int x)
{//相等向左插入
Node*p=t,*f=NULL;
while(p)
{
if (x<=p->data)
{
f=p;
p=p->l;
}
else
{
f=p;
p=p->r;
}
}
Node *s=new Node();
s->data=x;
s->l=s->r=NULL;
if (f==NULL)
t=s;
else if (x<=f->data)
f->l=s;
else
f->r=s;
return s;
}
二叉顺序树删除
Node *MyDelete(Node* &t,int x)
{
Node*p=t,*f=NULL;
while(p)
{
if (x==p->data)
break;
else if (x<p->data)
{
f=p;
p=p->l;
}
else
{
f=p;
p=p->r;
}
}
if (p)
{//已找到
if (!p->l&&!p->r)
{//叶子节点
if (!f)
t=NULL;//根节点
else
{
if (f->l==p)
f->l=NULL;
else
f->r=NULL;
}
}
else if (!p->l)
{//左不在
if (!f)
t=p->r;
else
{
if (f->l==p)
f->l=NULL;
else
f->r=NULL;
}
}
else if (!p->r)
{//右不在
if (!f)
t=p->l;
else
{
if (f->l==p)
f->l=NULL;
else
f->r=NULL;
}
}
else
{
Node *q=p,*s=p->l;
while(s->r)
{
q=s;
s=s->r;
}
p->data=s->data;
if (q!=p)
q->r=s->l;
else
q->l=s->l;
}
}
return p;
}
二叉顺序树深度
int Mydepth(Node *p)
{
if (!p)
return 0;
return max(Mydepth(p->l)+1,Mydepth(p->r)+1);
}
二叉顺序树遍历
void Qian(Node* p,int x,int deep)
{//前序遍历
if (p)
{
printf("%d ", p->data);
Qian(p->l,x+1,deep);
Qian(p->r,x+1,deep);
}
}