洛谷 p1030求先序排列——链式存储(指针)建树,遍历

【传送门】https://www.luogu.org/problemnew/show/P1030

【分析】

  后序字符串的结尾字符是root,在中序字符串中查找出这个字符的位置,然后递归建立左子树、右子树。本题涉及数学计算。

【AC代码】链式存储建树,遍历

//lg p1030 求先序   通过此题学习根据用中序、后序用指针建树,孩子表示法,输出先序 
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn=10;//字符串长度不超8,但要考虑到字符串是以'\0'结尾的,所以要开到9及以上,不可以只开到8 
char zx[maxn]="DEABFCHG",hx[maxn]="DEAFHGCB";
struct node{ //自引用结构。 
	char data;
	node *lt,*rt;
	/*
	“node *lt,*rt;”
	如果写成“node lt”,则属于非法,因为lt是另一个完整的结构,其内部还将包含它自己的成员lt,
	这第二个lt又是一个完整的结构,它还将包含自己的成员lt。
	但写成“node *lt;”,则合法,因为现在lt不是结构体,而是一个指针,编译器知道指针的长度。 
	*/
};
node *T;//申明一个指针,指向结构体node。在定义结构体时并不分配内存,只有定义了结构体变量时才分配,初始为NULL 
void make_tree(node *T,int l1,int r1,int l2,int r2){//*不能少,否则编辑错误。申明T是指向node的指针 	
	T->data=hx[r2];
	//寻找zx中root的位置 
	int t;
	for(int i=l1;i<=r1;i++)if(zx[i]==hx[r2]){
		t=i;break;
	}
	//递归建树 
	if(l1<t){
		T->lt=new node;
		make_tree(T->lt,l1,t-1,l2,l2+(t-l1)-1);
	}
	else{
		T->lt=new node;//这句话可以省略不写 
		T->lt=NULL;
	}
	if(t<r1){
		T->rt=new node;
		make_tree(T->rt,t+1,r1,l2+(t-l1),r2-1);
	}
	else{
		T->rt=new node;//这句话可以省略不写 
		T->rt=NULL;
	}	
}
void printxx(node* T){ //*不能少,否则编辑错误。申明T是指针 
	if(T){
		printf("%c",T->data);
		printxx(T->lt);
		printxx(T->rt);
	}
}
int main(){
//	freopen("in.txt","r",stdin);
//	scanf("%s%s",zx,hx);
	T=new node;//要求先申请新内存才可以对T进行操作 
	//cout<<T<<endl;
	make_tree(T,0,strlen(zx)-1,0,strlen(hx)-1); 
	//cout<<T<<endl;
	printxx(T);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_36314344/article/details/81504638