文章

11

粉丝

216

获赞

4

访问

96.6k

头像
使用string可以方便简洁地根据二叉树的先、中序遍历,构建二叉树
经验总结
发布于2021年2月24日 18:52
阅读数 9.8k

by 老猫 

#include <iostream>
#include <string>
#include <string.h>
using namespace std;

void postorder(string preorder ,string midorder)
{
	if(preorder.size()==0)
		return;
	char root=preorder[0];
	int index=midorder.find(root);
	string preorderleft=preorder.substr(1,index);//下一个前序的左子树
	string preorderright=preorder.substr(index+1);//下一个前序的右子树
	string midorderleft=midorder.substr(0,index);//下一个中序的左子树
	string midorderright=midorder.substr(index+1);//下一个中序的右子树
	postorder(preorderleft,midorderleft);
	postorder(preorderright,midorderright);
	cout<<root;
}

int main()
{
	string preorder,midorder;
	while(cin>>preorder>>midorder)
	{
		postorder(preorder ,midorder);
		cout<<endl;
	}
	return 0;
}

 

登录查看完整内容


登录后发布评论

暂无评论,来抢沙发