将一个采用链式存储的二叉树,其所有节点的左右子树进行交换

(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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值