递归
#include <iostream>
#include <deque>
#include <malloc.h>
using namespace std;
typedef struct BTNode {
int data;
struct BTNode *left, *right;
}*BiTree;
BiTree creat_bt(){
BiTree t;
int x;
cin >> x;
if (x==0) t=NULL;
else
{
t = (BiTree)malloc(sizeof(BTNode));
t->data = x;
t->left = creat_bt();
t->right = creat_bt();
}
return t;
}
void copyTree(BiTree &T, BiTree p){
T = p;
if(p == NULL)
return;
copyTree(T->left, p->left);
copyTree(T->right, p->right);
}
void copyTree1(BiTree &T, BiTree p){
if(p){
T = (BiTree)malloc(sizeof(BTNode));
T->data = p->data;
}else{
p = NULL;
return;
}
copyTree(T->left, p->left);
copyTree(T->right, p->right);
}
void PrintTreeByLevel(BiTree T)
{
if(T == NULL) return;
deque<BiTree> q;
q.push_back(T);
int curLevelNum;
while (q.size())
{
curLevelNum = (int)q.size();
while(curLevelNum-- > 0)
{
BiTree tmp = q.front();
q.pop_front();
printf("%d ", tmp->data);
if(tmp->left)
q.push_back(tmp->left);
if(tmp->right)
q.push_back(tmp->right);
}
printf("\n");
}
}
int main(){
BiTree p, T;
p = creat_bt();
cout << "原树:" << endl;
PrintTreeByLevel(p);
copyTree1(T, p);
cout << "新树:" << endl;
PrintTreeByLevel(p);
return 0;
}
非递归
#include <iostream>
#include <deque>
#include <malloc.h>
using namespace std;
typedef struct BTNode {
int data;
struct BTNode *left, *right;
}*BiTree;
BiTree creat_bt(){
BiTree t;
int x;
cin >> x;
if (x==0) t=NULL;
else
{
t = (BiTree)malloc(sizeof(BTNode));
t->data = x;
t->left = creat_bt();
t->right = creat_bt();
}
return t;
}
void copyTree(BiTree &T, BiTree p){
if(p == NULL) T = NULL;
else{
BiTree t;
t = T;
deque<BiTree> q;
q.push_back(p);
int curLevelNum;
while(q.size()){
curLevelNum = (int)q.size();
while(curLevelNum-- > 0)
{
BiTree tmp = q.front();
q.pop_front();
t = (BiTree)malloc(sizeof(BTNode));
t->data = tmp->data;
if(tmp->left){
t->left = (BiTree)malloc(sizeof(BTNode));
t->left->data = tmp->left->data;
}
if(tmp->right){
t->right = (BiTree)malloc(sizeof(BTNode));
t->right->data = tmp->right->data;
}
}
}
}
}
void PrintTreeByLevel(BiTree T)
{
if(T == NULL) return;
deque<BiTree> q;
q.push_back(T);
int curLevelNum;
while (q.size())
{
curLevelNum = (int)q.size();
while(curLevelNum-- > 0)
{
BiTree tmp = q.front();
q.pop_front();
printf("%d ", tmp->data);
if(tmp->left)
q.push_back(tmp->left);
if(tmp->right)
q.push_back(tmp->right);
}
printf("\n");
}
}
int main(){
BiTree p, T;
p = creat_bt();
cout << "原树:" << endl;
PrintTreeByLevel(p);
copyTree(T, p);
cout << "新树:" << endl;
PrintTreeByLevel(p);
return 0;
}