二叉排序树的合并(数据结构)

代码:

含注释,供参考

#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);//递归右子树
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

流光焰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值