problem D

题目链接
根据二叉树的前序遍历和中序遍历还原树,并输出后序遍历。

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e3+5;
char pre[maxn],in[maxn];
struct node{
	node* left, *right;
	char val;
};
node* create(int preL, int preR, int inL, int inR){
	if(preL > preR) return nullptr;
	node* root = new node;
	root->val = pre[preL];
	int k = inL;
	while(in[k] != pre[preL]){
		k++;
	}
	int left = k - inL;
	root->left = create(preL+1, preL+left,inL, k-1);
	root->right = create(preL+left+1, preR, k+1, inR);
	return root;
}
void inorder(node* root){
	if(root==nullptr) return;
	inorder(root->left);
	inorder(root->right);
	cout<<root->val;
}
int main(){
	while(cin>>pre>>in){
		int len = strlen(pre);
		node* root = create(0, len-1, 0, len-1);
		inorder(root);	
		cout<<endl;
	}
	return 0;
} 
全部评论

相关推荐

2025-12-15 14:25
云南大学 Java
lei22:入职可能会看学信网,最好别伪装,这个简历找实习肯定是够的,肯定会有收 28 届实习生的公司的,多投就行
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务