【数据结构】NOJ026 二叉排序树的合并(严9.38)

1. 题目

在这里插入图片描述

示例输入
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
示例输出
2 4 6 8 9 10 12 13 16 17 18 19 24 26

2. 代码

#include <iostream>

using namespace std;

typedef struct tree{
	int data;
	struct tree *lc, *rc;
}TNode;

TNode* CreateTree(){
	int tmp;
	cin >> tmp;
	if(tmp == -1){
		return NULL;
	}
	TNode* t = (TNode*)malloc(sizeof(TNode));
	t->data = tmp;
	t->lc = CreateTree();
	t->rc = CreateTree();
	return t;
}

TNode* Insert(TNode *t, int x){
	if(!t){
		t = (TNode*)malloc(sizeof(TNode));
		t->data = x;
		t->lc = NULL; t->rc = NULL;
		return t;
	}
	if(t->data == x) return t;
	if(t->data > x){
		t->lc = Insert(t->lc, x);
		return t;
	}
	if(t->data < x){
		t->rc = Insert(t->rc, x);
		return t;
	}
}

void Merge(TNode *t1, TNode *t2){
	if(t2){
		t1 = Insert(t1, t2->data);
		Merge(t1, t2->lc);
		Merge(t1, t2->rc);
	}
}

void InOrdOutpur(TNode *t){
	if(t){
		InOrdOutpur(t->lc);
		cout << t->data << " ";
		InOrdOutpur(t->rc);
	}
}

int main(){
	TNode *t1, *t2;
	t1 = CreateTree();
	t2 = CreateTree();
	Merge(t1, t2);
	InOrdOutpur(t1);
	return 0;
} 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值