清华大学机试-二叉树遍历

由给定的二叉树的前序遍历结果和中序便利结果,得到二叉树的后序遍历结果。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1005;
struct node{
	char data;
	node *lchild;
	node *rchild;
};
node tree[maxn];
int loc;
char str1[maxn],str2[maxn];
node *creat(){//申请一个节点空间 
	tree[loc].lchild = tree[loc].rchild=NULL;
	return &tree[loc++];
}
//核心,build函数

node *build(int s1,int e1,int s2,int e2){//由前序结果,中序结果构建二叉树 
	node *ret = creat();
	ret->data = str1[s1];
	int rootIdx;
	for(int i=s2;i<=e2;i++){
		if(str2[i]==str1[s1]){
			rootIdx = i;//找到根节点 
			break;
		}
	}
	if(rootIdx!=s2){//表示左子树不为空 
		ret->lchild = build(s1+1,s1+(rootIdx-s2),s2,rootIdx-1);
	}
	if(rootIdx!=e2){//表示右子树不为空 
		ret->rchild = build(s1+(rootIdx-s2)+1,e1,rootIdx+1,e2);
	}
	return ret;
} 
void postOrder(node *t){
	if(t->lchild!=NULL)
		postOrder(t->lchild);
	if(t->rchild!=NULL)
		postOrder(t->rchild);
	printf("%c",t->data);
} 


int main(){
	scanf("%s",str1);
	scanf("%s",str2);
	loc = 0;
	node *t = build(0,strlen(str1)-1,0,strlen(str2)-1);
	postOrder(t);
	printf("\n");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_37762592/article/details/88734964