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