代码:
含注释,供参考
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node*Lchild;
struct Node*Rchild;
} BSNode,*BSTree;
void CreateBST(BSTree*bst);//先序创建二叉排序树
void Join(BSTree b1,BSTree b2);//进行合并
void Insert(BSTree bst,int t);//将t插入到二叉排序树bst中
void Output(BSTree bst);//中序输出
int main()
{
BSTree BST1,BST2;
CreateBST(&BST1);//创建两个二叉排序树
CreateBST(&BST2);
Join(BST1,BST2);//进行合并
Output(BST1);//中序输出
return 0;
}
/*先序创建二叉排序树
*/
void CreateBST(BSTree*bst)
{
int data;
scanf("%d",&data);
if(data==-1)//data = -1,取消建立子树节点
*bst=NULL;
else
{
*bst=(BSTree)malloc(sizeof(BSNode));
(*bst)->data=data;
CreateBST(&((*bst)->Lchild));//递归建立左子树
CreateBST(&((*bst)->Rchild));//递归建立右子树
}
}
/*进行合并
*将b2合并到b1
*/
void Join(BSTree b1,BSTree b2)
{
if(b2)
{
Insert(b1,b2->data);//如果b2不为空,则将节点的数据插入到b1
Join(b1,b2->Lchild);//递归遍历b2,将数据插入b1中
Join(b1,b2->Rchild);
}
}
/*将t插入到二叉排序树bst中
*t:插入值
*/
void Insert(BSTree bst,int t)
{
int sign;//标志符号
BSTree pre;
while(bst)
{
pre=bst;//记录bst的父节点
if(t<bst->data)
{
bst=bst->Lchild;//如果t小于该节点数据,则将t与其左子树数据比较
sign=0;
}
else if(t>bst->data)
{
bst=bst->Rchild;//如果t小于该节点数据,则将t与其右子树数据比较
sign=1;
}
}
if(sign==0)//表示插入pre的左节点
{
pre->Lchild=(BSTree)malloc(sizeof(BSNode));
pre->Lchild->data=t;//完成插入
pre->Lchild->Lchild=NULL;
pre->Lchild->Rchild=NULL;
}
else
{
pre->Rchild=(BSTree)malloc(sizeof(BSNode));
pre->Rchild->data=t;//完成插入
pre->Rchild->Lchild=NULL;
pre->Rchild->Rchild=NULL;
}
}
/*中序输出
*/
void Output(BSTree bst)
{
if(bst)
{
Output(bst->Lchild);//递归左子树
printf("%d ",bst->data);
Output(bst->Rchild);//递归右子树
}
}