数据结构复习(交换左右子树)

来源:互联网 发布:淘宝上订机票靠谱吗 编辑:程序博客网 时间:2024/05/11 05:19

编写递归算法,将二叉树中所有结点的
左、右子树相互交换。

要求实现下列函数:
void Exchange(BiTree &bt);
/* Exchange the left and right leaves of */
/* bitree whose root node is bt          */

二叉链表类型定义:
typedef struct BiTNode {
    TElemType data;
    BiTNode  *lchild, *rchild;
} BiTNode, *BiTree;

void Exchange(BiTree &bt)
/* Exchange the left and right leaves of */
/* bitree whose root node is bt          */
{
    BiTree pb;
    if(bt){
        //交换左右子树
        pb=bt->lchild;
        bt->lchild=bt->rchild;
        bt->rchild=pb;   
        //先序递归左右子树
        Exchange(bt->lchild);
        Exchange(bt->rchild);
    }
    else
        return;   
}

//注:不能使用中序遍历递归法去解决这个问题

原创粉丝点击