您的位置:首页 > 其它

POJ 2255 Tree Recovery

2012-08-03 11:01 375 查看
已知二叉树的前序遍历序列和中序遍历序列,求后序遍历序列。

先递归构造二叉树,再递归后序遍历。

思路:

前序序列的第一个结点为要构造的二叉树的根节点,在中序序列中查找此节点,则其左为要构造的二叉树的左子树的中序序列,其右为要构造的二叉树的右子树的中序序列。而前序序列根节点后面分别跟着它的左子树和右子树的前序序列。有了根节点在中序序列中的位置,就知道了左子树和右子树的前序序列分别占据了前序序列中的那些位置,这样,就分别知道了两棵子树所代表的子序列。然后在构造了根结点后,就可以递归调用函数自身来分别构造根节点的左子树和右子树。

以上为二叉树的构造即恢复。

后序遍历二叉树也用递归。

#include <iostream>
#include<cstdio>
#include <string>//c++中的string类包含find,substr函数,或者用#include<algorithm>
using namespace std;
struct Node{
char data;
Node* lchild;
Node* rchild;
};
Node* CreateTree(string pre,string in)//递归创建二叉树
{
Node* root = NULL;
if(pre.length()>0)
{
root = new Node;
root->data = pre[0];
int index = in.find(root->data);
root->lchild = CreateTree(pre.substr(1,index),in.substr(0,index));//从一个字符串复制一个从指定位置开始,并具有指定长度的子字符串
root->rchild = CreateTree(pre.substr(index+1),in.substr(index+1));//如果 length 为 0 或负数,将返回一个空字符串。如果没有指定该参数,则子字符串将延续到字符串的结尾
}
return root;
}

void PostOrder(Node* root)//递归后序遍历
{
if(root!=NULL)
{
PostOrder(root->lchild);
PostOrder(root->rchild);
cout<<root->data;
}
}

int main()
{
string pre_str,in_str;
while (cin>>pre_str>>in_str)
{
Node* rt = CreateTree(pre_str,in_str);
PostOrder(rt);
cout<<endl;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: