二叉排序树合并其实就是遍历一个树插入另外一个树。
#include <stdio.h>
#include <stdlib.h>
typedef struct BiNode
{
int data;
struct BiNode *leftchild,*rightchild;
}BiNode,*BiTree;
//初始化二叉排序树
BiTree InitTree(BiTree T)
{
int e;
scanf("%d",&e);
if(e!=-1)
{
T=(BiNode*)malloc(sizeof(BiNode));
T->data=e;
T->leftchild=InitTree(T->leftchild);
T->rightchild=InitTree(T->rightchild);
}
else
{
T=NULL;
}
return T;
}
//二叉排序树插入
BiTree insertBST(BiTree T,int val)//bt应该为引用,因为层层改变
{
if(T==NULL)
{
BiTree S;
S=(BiTree)malloc(sizeof(BiNode));
S->data=val;
S->leftchild=NULL;
S->rightchild=NULL;
T=S;
}
else
{
if(val<T->data) T->leftchild=insertBST(T->leftchild,val);
else T->rightchild=insertBST(T->rightchild,val);
}
return T;
}
//二叉排序树的合并
void mergeTree(BiTree T,BiTree S)
{
if(S==NULL)
return;
mergeTree(T,S->leftchild);
T=insertBST(T,S->data);
mergeTree(T,S->rightchild);
}
//中序遍历
void PrintBTS(BiTree T)
{
if(T==NULL)
return;
PrintBTS(T->leftchild);
printf("%d ",T->data);
PrintBTS(T->rightchild);
}
int main()
{
BiTree T,S;
T=InitTree(T);
S=InitTree(S);
mergeTree(T,S);
PrintBTS(T);
return 0;
}