二叉排序树的合并(严9.38)

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;
}

把上一题的代码改改就能过,主要想法就是把一棵树插入到另一棵树里

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值