由后序遍历与中序遍历确定前序遍历

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

struct Node
{
    Node * lchild;
    Node * rchild;
    char c;
};

Node* build(string in ,string pos)
{
	Node* t=NULL;
	if(in.size()>0)
	{
		t=new Node();
		t->c=pos[pos.length()-1];
		t->lchild=NULL;
		t->rchild=NULL;
	}
	if(in.size()>1)
	{
		int root=0;
		for(int i=0;i<in.size();i++)
			if(in[i]==t->c)
				{
					root=i;
                    break;
				}
		string pos_left = pos.substr(0, root);
		string in_left = in.substr(0,root);
		t->lchild=build(in_left, pos_left);

		string pos_right = pos.substr(root, pos.length()-1-root);
		string in_right = in.substr(root+1, in.size()-root-1);
		t->rchild=build(in_right, pos_right);
	}
	return t;
}

void PreOrder(Node* t)
{
	cout<<t->c;
	if(t->lchild)PreOrder(t->lchild);
	if(t->rchild)PreOrder(t->rchild);
}

int main()
{
    string in, pos;
    cin>>in>>pos;
    Node* t= build(in, pos);
    PreOrder(t);
     
    cout<<endl;

    return 0;
}

  

posted @ 2016-12-13 01:42  KennyRom  阅读(295)  评论(0编辑  收藏  举报