题目:输入一颗二元查找树,将该树转换为它的镜像,
即在转换后的二元查找树中,左子树的结点都大于右子树的结点。
用递归和循环两种方法完成树的镜像转换。
例如输入:
8
/ \
6 10
/\ /\
5 7 9 11
输出:
8
/ \
10 6
/\ /\
11 9 7 5
#include "stdlib.h"
#include "stdio.h"
typedef struct BTNode
{
int data;
struct BTNode *lnode;
struct BTNode *rnode;
}BTNode;
BTNode *CreateTree(int pre[], int in[], int l1, int r1, int l2, int r2){
BTNode *s;
int i;
if(l1 > r1)
return NULL;
s = (BTNode *)malloc(sizeof(BTNode));
s->lnode = s->rnode = NULL;
for(i=l2; i<=r2; ++i){
if(pre[l1] == in[i]){
break;
}
}
s->data = in[i];
s->lnode = CreateTree(pre, in, l1+1, l1+i-l2, l2, i-1);
s->rnode = CreateTree(pre, in, l1+i-l2+1, r1, i+1, r2);
return s;
}
void PrePrint(BTNode *p){
if(p != NULL){
printf("%d ", p->data);
PrePrint(p->lnode);
PrePrint(p->rnode);
}
}
void InPrint(BTNode *p){
if(p != NULL){
InPrint(p->lnode);
printf("%d ", p->data);
InPrint(p->rnode);
}
}
//Use recursion method to implement
BTNode *MakeMirror(BTNode *p){
if(p != NULL){
BTNode *leftNode = p->lnode;
BTNode *rightNode = p->rnode;
p->lnode = MakeMirror(rightNode);
p->rnode = MakeMirror(leftNode);
}
return p;
}
#define maxSize 50
//Use non-recursion method to implement
BTNode *MakeMirror_2(BTNode *p){
BTNode *que[maxSize];
int front, rear;
front = rear = 0;
BTNode *s = p;
if(s != NULL){
rear = (rear+1)%maxSize;
que[rear] = p;
while(front != rear){
front = (front+1)%maxSize;
s = que[front];
BTNode *leftNode = s->lnode;
BTNode *rightNode = s->rnode;
//Exchange child tree
s->lnode = rightNode;
s->rnode = leftNode;
if(leftNode != NULL){
rear = (rear+1)%maxSize;
que[rear] = leftNode;
}
if(rightNode != NULL){
rear = (rear+1)%maxSize;
que[rear] = rightNode;
}
}
}
return p;
}
void main(){
int pre[] = {8, 6, 5, 7, 10, 9, 11};
int in[] = {5, 6, 7, 8, 9, 10, 11};
BTNode *p;
p = CreateTree(pre, in, 0, 6, 0, 6);
p = MakeMirror_2(p);
PrePrint(p);
}