题目:
输入一颗二元查找树,将该树转换为它的镜像,即在转换后的二元查找树中,左子树的结点都大于右子树的结点。
用递归和循环两种方法完成树的镜像转换。
例如输入:
8
/ \
6 10
/\ /\
5 7 9 11
输出:
8
/ \
10 6
/\ /\
11 9 7 5
分析:
递归程序设计比较简单
访问一个节点,只要不为空则交换左右孩子,然后分别对左右子树递归。
非递归实质是需要我们手动完成压栈,思想是一致的
代码如下(GCC编译通过):
#include "stdio.h"
#include "stdlib.h"
#define MAXSIZE 8
typedef struct node
{
int data;
struct node * left;
struct node * right;
}BTree;
void swap(BTree ** x,BTree ** y);//交换左右孩子
void mirror(BTree * root);//递归实现函数声明
void mirrorIteratively(BTree * root);//非递归实现函数声明
BTree * CreatTree(int a[],int n);//创建二叉树(产生二叉排序树)
void Iorder(BTree * root);//中序遍历查看结果
int main(void)
{
int array[MAXSIZE] = {5,3,8,7,2,4,1,9};
BTree * root;
root = CreatTree(array,MAXSIZE);
printf("变换前:\n");
Iorder(root);
printf("\n变换后:\n");//两次变换,与变化前一致
mirror(root);
mirrorIteratively(root);
Iorder(root);
printf("\n");
return 0;
}
void swap(BTree ** x,BTree ** y)
{
BTree * t = * x;
* x = * y;
* y = t;
}
void mirror(BTree * root)
{
if(root == NULL)//结束条件
return;
swap(&(root->left),&(root->right));//交换
mirror(root->left);//左子树递归
mirror(root->right);//右子树递归
}
void mirrorIteratively(BTree * root)
{
int top = 0;
BTree * t;
BTree * stack[MAXSIZE+1];
if(root == NULL)
return;
//手动压栈、弹栈
stack[top++] = root;
while(top != 0)
{
t = stack[--top];
swap(&(t->left),&(t->right));
if(t->left != NULL)
stack[top++] = t->left;
if(t->right != NULL)
stack[top++] = t->right;
}
}
//产生二叉排序树
BTree * CreatTree(int a[],int n)
{
BTree * root ,*p,*cu,*pa;
int i;
root = (BTree *)malloc(sizeof(BTree));
root->data = a[0];
root->left = root->right =NULL;
for(i=1;i<n;i++)
{
p = (BTree *)malloc(sizeof(BTree));
p->data = a[i];
p->left = p->right =NULL;
cu = root;
while(cu)
{
pa = cu;
if(cu->data > p->data)
cu = cu->left;
else
cu = cu->right;
}
if(pa->data > p->data)
pa->left = p;
else
pa->right = p;
}
return root;
}
//中序遍历
void Iorder(BTree * root)
{
if(root)
{
Iorder(root->left);
printf("%3d",root->data);
Iorder(root->right);
}
}