二叉树交换左右子树非递归算法

基本思想:(先序,中序,后序,层次遍历都可以实现,本质就是就是交换每个节点的左右孩子)

(1)若树非空,则入队

(2)若队头指针的左右孩子非空,则入队。

(3)交换对头节点的左右孩子,出队。

(4)重复步骤(2)(3)直到队列为空

(5)交换结束。

算法:

 1 void Exchange(BinTree BT){
 2     Queue Q;
 3     initQueue(Q);
 4     if(BT!=NULL){
 5         EnQueue(Q,BT);
 6     }
 7     while(!isEmptyQueue(Q)){
 8         BinTree p=QueueHead(Q);
 9         if(p->lchild!=NULL){
10             EnQueue(Q,p->lchild);
11         }
12         if(p->rchild!=NULL){
13             EnQueue(Q,p->rchild);
14         }
15         BinTree temp;
16         temp=p->lchild;
17         p->lchild=p->rchild;
18         p->rchild=temp;
19     }
20 }

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

导航