代码改变世界

POJ 2255 Tree Recovery

2012-03-09 14:35  咆哮的马甲  阅读(209)  评论(0编辑  收藏  举报

根据二叉树的先序和中序遍历的结果,构造出这棵树后续遍历的结果。

思路是根据先序遍历的节点将中序遍历的结果连续二分,递归即可还原树的本来面目。

将找到的子树根节点压栈再退栈即可后序输出二叉树。

 

#include <iostream>
#include <string>
#include <stack>

using namespace std;

stack<char> s;

void RecreateTree(string& pre, string& in)
{
if(!pre.empty() && !in.empty())
{
char root;

for(int i=0; i<pre.length();i++)
{
char c = pre[i];
if(in.find(c) != -1)
{
root = c;
s.push(root);
break;
}
}

size_t rootIndex = in.find(root);

if(rootIndex != in.length()-1)
{
string right = in.substr(rootIndex+1,in.length()-rootIndex-1);
RecreateTree(pre,right);
}

if(rootIndex != 0)
{
string left = in.substr(0,rootIndex);
RecreateTree(pre,left);
}
}
}

int main()
{
string pre;
string in;

while(cin>>pre)
{
cin>>in;

RecreateTree(pre,in);

while(!s.empty())
{
char c= s.top();
s.pop();
cout<<c;
}
cout<<endl;
}
return 0;
}