如何复制一棵二叉树

基本思路:

(1)如果树非空,则复制该根节点,同时,把这两个节点分别进入QueueFormer,QueueCopy

(2)让pFormer指向QueueFormer的对头,pCopy指向QueueCopy的队头。

(3)pFormer的左右孩子,若非空,则复制其data,同时修改pCopy的左右孩子的指针,并对非空节点都入站操作,

(4)对QueueFormer和QueueCopy出栈(对头节点已完成复制)

(5)重复(2)~(4)直到队列为空

(6)返回头指针,复制完成。

代码:

 1 BinTree CopyTree(BinTree BT){
 2     Queue QueueFormer;
 3     Queue QueueCopy;
 4     BinTree root=NULL;
 5     init(QueueFomer);
 6     init(QueueCopy);
 7     if(BT!=NULL){
 8         root=(BinTree)malloc(sizeof(BinTNode));
 9         root->data=BT->data;
10         root->lchild=NULL;
11         root->rchild=NULL:
12         EnQueue(QueueFormer,BT);
13         EnQueue(QueueCopy,root);
14     }
15     while(!isEmptyQueue(QueueFormer)){
16         BinTree pFomer=QueueHeader(QueueFormer);
17         BinTree pCopy=QueueHeader(QueueCopy);
18         if(pFormer->lchild!=NULL)//复制左孩子
19         {
20              BinTree temp=(BinTree)malloc(sizeof(BinTNode));
21              temp->data=pFormer->lchild->data;
22              temp->lchild=NULL;
23              temp->rchild=NULL:
24              pCopy->lchild=temp;
25              EnQueue(QueueFormer,pFormer->lchild);
26              EnQueue(QueueCopy,temp):
27         }
28         if(pFormer->rchild!=NULL)//复制右孩子
29         {
30              BinTree temp=(BinTree)malloc(sizeof(BinTNode));
31              temp->data=pFormer->rchild->data;
32              temp->lchild=NULL;
33              temp->rchild=NULL:
34              pCopy->rchild=temp;
35              EnQueue(QueueFormer,pFormer->rchild);
36              EnQueue(QueueCopy,temp);
37         }
38         DeQueue(QueueFormer);
39         DeQueue(QueueCopy);
40     }
41 return root;
42 }

 

posted on 2012-05-23 14:05  为梦飞翔  阅读(5622)  评论(0编辑  收藏  举报

导航