将一棵二叉树的全部节点的左右子树交换顺序

模拟了层次遍历的算法。

#include<iostream>
#include<malloc.h>
#include<queue>
#include<list>
using namespace std;
struct node
{
	char c;
	node *lchild,*rchild;
};
char pre[100];
char mid[100];
void build(node* &t,int start1,int end1,int start2,int end2)
{
	int i=start2;
	while(pre[start1]!=mid[i])
		i=i+1;
	t=(node*)malloc(sizeof(node));
	t->c=pre[start1];
	if(i==start2)
		t->lchild=NULL;
	else build(t->lchild,start1+1,start1+i-start2,start2,i-1);
	if(i==end2)
		t->rchild=NULL;
	else build(t->rchild,start1+i-start2+1,end1,i+1,end2);
}
list<node*> que;
list<node*> temp;
void exchange(node *t)
{
	if(!temp.empty())
		temp.clear();
	temp.push_back(t);
	while(!temp.empty())
	{
		node* q;
		q=temp.front();
		if(q->lchild)
			temp.push_back(q->lchild);
		if(q->rchild)
			temp.push_back(q->rchild);
		temp.pop_front();
		node *r;
		r=q->lchild;
		q->lchild=q->rchild;
		q->rchild=r;
	}
}
void visit(node *t)
{
	if(!que.empty())
		que.clear();
	que.push_back(t);
	while(!que.empty())
	{
		node *x;
		x=que.front();
		cout<<x->c;
		que.pop_front();
		if(x->lchild)
			que.push_back(x->lchild);
		if(x->rchild)
			que.push_back(x->rchild);
	}
}
int main()
{
	node *tree;
	int length;
	while(1==1)
	{
		cout<<"pre"<<endl;
		cin>>pre;
		cout<<"mid"<<endl;
		cin>>mid;
		length=strlen(mid);
		build(tree,0,length-1,0,length-1);
		exchange(tree);
		visit(tree);
	}
	return 0;
}


  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值