题目:
输入一颗二元查找树,将该树转换为它的镜像,
即在转换后的二元查找树中,左子树的结点都大于右子树的结点。用递归和循环两种方法完成树的镜像转换。
例如输入:
8
/ \
6 10
/\ /\
5 7 9 11
输出:
8
/ \
10 6
/\ /\
11 9 7 5
方法一:递归
可以用递归方法对每一个结点交换左右子树。
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include "TREE.h"
void Convert(BTNode *L);
int main()
{
BTNode *L=NULL;
CreateTree(&L); //建立二叉树
printf("Before convert,the nodes in the tree are: \n");
OutputTree(L); //首先输出转换前的二叉树的先序遍历元素
printf("\n");
Convert(L); //转换二叉树
printf("After convert,the nodes in the tree are: \n");
OutputTree(L); //输出转换后的二叉树的先序遍历元素
printf("\n");
return 0;
}
void Convert(BTNode *L) //递归转换当前结点的左右子树
{
BTNode *temp=NULL;
if (L)
{
temp=L->lChild; //交换左右子树
L->lChild=L->rChild;
L->rChild=temp;
Convert(L->lChild);
Convert(L->rChild);
}
}
头文件TREE.H为建立二叉树的相关内容,如下所示:
#ifndef TREE_H
#define TREE_H
#include <stdio.h>
#include <stdlib.h>
typedef struct treeNode
{
struct treeNode *lChild;
struct treeNode *rChild;
char num;
}BTNode;
void CreateTree(BTNode **L);//给出先序遍历,建立二叉树,无孩子结点用#代替。
//具体表述可参考http://acm.njupt.edu.cn/acmhome/problemdetail.do?&method=showdetail&id=1019
void OutputTree(BTNode *L); //先序遍历
void CreateTree(BTNode **L) //注意这里传的是指针的地址!!!
{
char ch;
ch=getchar();
getchar();
if (ch=='#')
{
(*L)=NULL;
}
else
{
*L=(BTNode*)malloc(sizeof(BTNode));
(*L)->num=ch;
CreateTree(&((*L)->lChild));
CreateTree(&((*L)->rChild));
}
}
void OutputTree(BTNode *L)
{
if (L)
{
printf("%c ",L->num);
OutputTree(L->lChild);
OutputTree(L->rChild);
}
}
#endif
方法二:循环(利用BFS层次遍历每个结点,也可利用DFS)
给出代码:
#include <stdio.h>
#include <stdlib.h>
#include "TREE.h"
int front=0,rear=0;
BTNode * Queue[20];
void Push(BTNode *s)
{
Queue[rear++]=s;
}
void Pop()
{
front++;
}
BTNode *GetTop()
{
return Queue[front];
}
BTNode* Convert(BTNode *L);
int main()
{
BTNode *L=NULL;
CreateTree(&L);
printf("Before convert,the nodes in the tree are: \n");
OutputTree(L);
printf("\n");
L=Convert(L);
printf("After convert,the nodes in the tree are: \n");
OutputTree(L);
printf("\n");
return 0;
}
BTNode *Convert(BTNode *L)
{
BTNode *temp,*cur;
Push(L);
while(front<rear)
{
cur=GetTop(); //获取栈中首元素
if (cur->lChild!=NULL) //若有左节点,压入队列
{
Push(cur->lChild);
}
if (cur->rChild!=NULL) //若有右结点,压入队列
{
Push(cur->rChild);
}
temp=cur->lChild; //交换当前结点的左右子节点
cur->lChild=cur->rChild;
cur->rChild=temp;
Pop(); //弹出首元素
}
return L;
}