二叉樹交換左右子樹
#include<stdio.h>
#include<malloc.h>
typedef struct Node{
int data;
struct Node* LChild;
struct Node* RChild;
}Tree;
void createTree(Tree **T)
{
int data = 1;
scanf("%d",&data);
if ( data != 0)
{
*T = (Tree *)malloc(sizeof(Tree));
(*T)->data = data;
(*T)->LChild = NULL;
(*T)->RChild = NULL;
createTree(&(*T)->LChild);
createTree(&(*T)->RChild);
}
}
void printTree(Tree *T)
{
if ( T!=NULL)
{
printf("%d ",T->data);
printTree(T->LChild);
printTree(T->RChild);
}
}
Tree * exchange_rootFirlst(Tree* T) //先序遍歷
{
if(T!=NULL)
if(T->LChild!=NULL||T->RChild!=NULL)
{
Tree *p,*q;
p = exchange_rootFirlst(T->LChild);
q = exchange_rootFirlst(T->RChild);
T->LChild = q;
T->RChild = p;
}
return T;
}
void exchange_rootLast(Tree* T) // 後序遍歷
{
if(T!=NULL)
if(T->LChild!=NULL||T->RChild!=NULL)
{
Tree *p,*q;
q = T->RChild;
p = T->LChild;
T->LChild = q;
T->RChild = p;
exchange_rootLast(T->LChild);
exchange_rootLast(T->RChild);
}
}
Tree * exchange_rootMiddle(Tree* T) //類似於中序遍歷
{
if(T!=NULL)
if(T->LChild!=NULL||T->RChild!=NULL)
{
Tree *p,*q;
p = exchange_rootMiddle(T->LChild);
q = T->RChild;
T->RChild = p;
T->LChild = q;
q = exchange_rootMiddle(T->RChild);
}
return T;
}
void main()
{
Tree *T ;
createTree(&T);
printTree(T);
printf("\n");
exchange_rootFirlst(T);
printTree(T);
printf("\n");
exchange_rootLast(T);
printTree(T);
printf("\n");
exchange_rootMiddle(T);
printTree(T);
printf("\n");
}
交換二叉樹的左右子樹可採用先序遍歷,中序遍歷,後序遍歷完成。先序與後序不需要考慮太多,簡單交換即可。中序遍歷要考慮到,若左子樹已經交換過了,那麼左右一交換,原來的左變為右了,原來的右子樹變為左子樹,而新的左子樹是沒有進行交換過的。