tree
typedef struct node
{
node *left,right;
int data;
} node;
// Khai báo kiểu con trỏ chỉ đến nút
typedef struct node *tree;
Khởi tạo cây rỗng
void CreateTree(tree &t)
{
t=NULL;
}
Kiểm tra cây có bị rỗng không
bool EmptyTree(tree t)
{
return ( t == NULL);
}
tree SearchTree(tree t, int x)
{
if(x<t->data)
SearchTree(t->left,x);
else if(x>t->data)
SearchTree(t->right,x);
else
return t;
}
void InsertTree(tree &t, int x)
{
if(t==NULL) // !EmptyTree(t)
{
t = (tree) malloc(sizeof(node));
t->data = x;
t->left = NULL;
t->right = NULL;
}
else if(x<t->data)
InsertTree(t->left,x);
else
InsertTree(t->right,x);
}
void Del (tree &p, tree &q)
{if(p->right !=NULL)
Del(p->right,q);
else
{q->data = p->data;
q = p;
p = q->left;
}
}
gia su xoa nut 10
void DeleteTree (tree &t, int x)
{
tree q;
if( x<t->data )
DeleteTree(t->left,x);
else if ( x>t->data)
DeleteTree(t->right,x);
else
{
q = t;
if (t ->right = = NULL)t = t ->left;else if (t->left == NULL)
t = t ->right;else
Del(t->left,q) ;
free (q);
}
}
void LNR(tree t,int muc)
{
cout<<endl;
if(t!=NULL)
{
muc++;
LNR(t->left,muc);
cout<<setw(muc*5)<<t->data;
LNR(t->right,muc);
muc--;
}
}
void LRN(tree t,int muc)
{
cout<<endl;
if(t!=NULL)
{
muc++;
LRN(t->left,muc);
LRN(t->right,muc);
muc--;
cout<<setw(muc*5)<<t->data;
}
}
void NLR(tree t,int muc)
{
cout<<endl;
if(t!=NULL)
{
cout<<setw(muc*5)<<t->data;muc++;
NLR(t->left,muc);
NLR(t->right,muc);
muc--;
}
}
Bạn đang đọc truyện trên: AzTruyen.Top