Description
试编写程序,将两棵二叉排序树合并为一棵二叉排序树。
Input
按照先序序列,分两行输入两棵二叉排序树各结点(结点值大于0),其中-1表示取消建立子树结点。
Output
按照中序序列输出合并后的二叉排序树。
-
Sample Input
12 8 4 -1 -1 10 -1 -1 16 13 -1 -1 18 -1 -1 17 6 2 -1 -1 9 -1 -1 24 19 -1 -1 26 -1 -1
-
Sample Output
2 4 6 8 9 10 12 13 16 17 18 19 24 26
#include<stdio.h>
#include<stdlib.h>
typedef struct BinNode{
int data;
struct BinNode *lchild;
struct BinNode *rchild;
}BinNode,*BinTree;
void CreateBinTree(BinTree *tree)
{
int ch;
scanf("%d",&ch);
if(ch == -1)
{
(*tree) = NULL;
}
else
{
*tree = (BinTree)malloc(sizeof(BinNode));
(*tree)->data = ch;
CreateBinTree(&((*tree)->lchild));
CreateBinTree(&((*tree)->rchild));
}
}
void Inorder(BinTree T)
{
if(T)
{
Inorder(T->lchild);
printf("%d ",T->data);
Inorder(T->rchild);
}
}
void Insert(BinTree *T,int key)
{
if(!(*T))
{
(*T) = (BinTree)malloc(sizeof(BinNode));
(*T)->data = key;
(*T)->lchild = (*T)->rchild = NULL;
return;
}
if(key == (*T)->data )
return;
if(key > (*T)->data )
Insert( &((*T)->rchild), key );
else
Insert( &((*T)->lchild), key );
}
void InsertBST(BinTree T1,BinTree T2)
{
if(T2)
{
InsertBST(T1,T2->lchild);
Insert(&T1,T2->data);
InsertBST(T1,T2->rchild);
}
}
int main(){
BinTree T1 = NULL;
BinTree T2 = NULL;
CreateBinTree(&T1);
CreateBinTree(&T2);
InsertBST(T1,T2);
Inorder(T1);
printf("\n");
return 0;
}
把上一题的代码改改就能过,主要想法就是把一棵树插入到另一棵树里