1、递归算法实现交换左右子树
void ReChange(BiTree T)
{
BiTree p = NULL;
if (T == NULL) {
return ;
} else {
p = T->lchild;
T->lchild = T->rchild;
T->rchild = p;
}
ReChange(T->lchild);
ReChange(T->rchild);
}
2、完整代码测试
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<iostream>
using namespace std;
typedef char DataType;
#define MAXSIZE 100
typedef struct node
{
DataType data;
struct node *lchild;
struct node *rchild;
}BiTreeNode,*BiTree;
//先序建立二叉树
void CreateBiTree(BiTree &root)
{
char c;
cin>>c;
if(c=='#')
{
root=NULL;
}
else
{
root=(BiTree)malloc(sizeof(BiTreeNode));
root->data=c;
CreateBiTree(root->lchild);
CreateBiTree(root->rchild);
}
}
//递归实现先序遍历
void PreOrder(BiTree root)
{
if(root!=NULL)
{
cout<<root->data<<" ";
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
//递归实现交换左右子树
void ReChange(BiTree T)
{
BiTree p = NULL;
if (T == NULL) {
return ;
} else {
p = T->lchild;
T->lchild = T->rchild;
T->rchild = p;
}
ReChange(T->lchild);
ReChange(T->rchild);
}
//测试序列:ABDG###E##CF#H###
int main()
{
BiTree root;
CreateBiTree(root);
PreOrder(root);
cout<<endl;
ReChange(root);
PreOrder(root);
cout<<endl;
system("pause");
return 0;
}