#include
#include
#include
#define true 1
#define false 0
#define STACKSIZE 10
typedef struct bstnode{
int data;
struct bstnode *lchild,*rchild;
}bstnode;
bstnode* searchBST(bstnode *h,int key)
{
if(h==NULL)return NULL;
else if(h->data==key){
printf("h:%x,search success!/n",h);
return h;
}
else if(h->datarchild,key);
else return searchBST(h->lchild,key);
}
void createTree(bstnode **h)
{
int i;
scanf("%d",&i);
if(i==0)(*h)=NULL;
else{
(*h)=(bstnode*)malloc(sizeof(bstnode));
(*h)->data=i;
(*h)->lchild=(*h)->rchild=NULL;
createTree(&((*h)->lchild));
createTree(&((*h)->rchild));
}
}
void insertBST(bstnode ** h,int key)
{
if(searchBST(*h,key)==NULL){
bstnode *p=malloc(sizeof(bstnode));
p->data=key;
p->lchild=p->rchild=NULL;
if((*h)==NULL)(*h)=p;
else if(key<(*h)->data)insertBST(&((*h)->lchild),key);
else insertBST(&((*h)->rchild),key);
}
}
bstnode* deleteBST(bstnode*root,int key)
{
//f points to father node.
bstnode *p,*f,*s,*q;
p=root;f=NULL;
//find out the node which data value equals key,and record its father node point.
while(p){
if(p->data==key)break;
else if(keydata){
f=p; p=p->lchild;
}
else {
f=p; p=p->rchild;
}
}//end while
if(p==NULL)return root;
if(p->lchild==NULL){//left child is null.
if(f==NULL)root=p->rchild;
else if(f->lchild==p)f->lchild=p->rchild;
else f->rchild=p->rchild;
free(p);
}
else { //p have left child
q=p;s=p->lchild;
while(s->rchild){
q=s;
s=s->rchild;
}
if(q==p)q->lchild=s->lchild;
else q->rchild=s->lchild;
p->data=s->data;
free(s);
}//end for p have left child
return root;
}
void preorder(bstnode *h)
{
if(h!=NULL){
printf("%d ",h->data);
preorder(h->lchild);
preorder(h->rchild);
}
}
void inorder(bstnode *h)
{
if(h){
inorder(h->lchild);
printf("%d ",h->data);
inorder(h->rchild);
}
}
bstnode* get_last(bstnode*h){
if(h!=NULL)
while(h->rchild!=NULL)
{
h=h->rchild;
}
return h;
}
bstnode * treeToList(bstnode*h){
if(h==NULL)return NULL;
else {
bstnode* pre=treeToList(h->lchild);
bstnode* post=treeToList(h->rchild);
if(pre){
get_last(pre)->rchild=h;
h->lchild=get_last(pre);
}
if(post){
post->lchild=h;
h->rchild=post;
}
if(pre) return pre;
else return h;
}
}
int main()
{
bstnode *h;
int val;
printf("input a int and a BST tree:/n");
do{
scanf("%d",&val);
insertBST(&h,val);
}while(val!=0);
// preorder(h);
// printf("/n");
inorder(h);
printf("/n");
bstnode* head=treeToList(h);
while(head){
printf("%d ",head->data);
head=head->rchild;
}
printf("/n");
return 0;
}
二叉排序树转换成双链表
最新推荐文章于 2024-06-08 15:26:15 发布