(C++实现,借助结构体类型的数组模拟出队入队操作)
1.创建一棵二叉树
2.层次遍历输出这棵二叉树
3.将左右子树进行反转
4.层次遍历输出反转后的二叉树
#include <iostream>
#include <cstdlib>
using namespace std;
# define MaxSize 10
typedef struct BTNode{
int data;
struct BTNode *lchild,*rchild;
}BiTree;
/*
1
/ \
2 3
/ \ / \
4 5 6 7
*/
void createBTree(BiTree **root){
*root=(struct BTNode *)malloc(sizeof(struct BTNode));
(*root)->data=1;
BiTree *n2,*n3,*n4,*n5,*n6,*n7;
n2=(struct BTNode *)malloc(sizeof(struct BTNode));
n3=(struct BTNode *)malloc(sizeof(struct BTNode));
n4=(struct BTNode *)malloc(sizeof(struct BTNode));
n5=(struct BTNode *)malloc(sizeof(struct BTNode));
n6=(struct BTNode *)malloc(sizeof(struct BTNode));
n7=(struct BTNode *)malloc(sizeof(struct BTNode));
n2->data=2;
n3->data=3;
n4->data=4;
n5->data=5;
n6->data=6;
n7->data=7;
(*root)->lchild=n2; (*root)->rchild=n3;
n2->lchild=n4; n2->rchild=n5;
n3->lchild=n6; n3->rchild=n7;
n4->lchild=NULL; n4->rchild=NULL;
n5->lchild=NULL; n5->rchild=NULL;
n6->lchild=NULL; n6->rchild=NULL;
n7->lchild=NULL; n7->rchild=NULL;
}
/*实现中序遍历的函数*/
void InOrder(BiTree *root){
if(root==NULL)
return;
else{
InOrder(root->lchild);
cout<<root->data<<endl;
InOrder(root->rchild);
}
}
/*实现层次遍历的函数*/
void level(BiTree *root){
int front,rear;
BiTree *q;
front=rear=0;
BTNode *que[MaxSize];
if(root!=NULL){
rear=(rear+1)%MaxSize;
que[rear]=root;
/*判断当前队列是否为空*/
while(front!=rear){
front=(front+1)%MaxSize;
q=que[front];
cout<<q->data<<" ";
/*判断左子树是否为空,不为空执行入队操作*/
if(q->lchild!=NULL){
rear=(rear+1)%MaxSize;
que[rear]=q->lchild;
}
/*判断左子树是否为空,不为空执行入队操作*/
if(q->rchild!=NULL){
rear=(rear+1)%MaxSize;
que[rear]=q->rchild;
}
}
}
cout<<endl;
}
void change(BiTree *root){
BiTree *temp;
if (root == NULL) return;
temp=root->lchild;
root->lchild=root->rchild;
root->rchild=temp;
change(root->lchild);
change(root->rchild);
}
int main(){
BiTree *root;
createBTree(&root);
cout <<"未旋转之前的二叉树为:";
level(root);
change(root);
cout <<"旋转之后的二叉树为:";
level(root);
return 0;
}