二叉树——(先序序列+中序序列)=后序序列 poi2255

来源:互联网 发布:win2008 dhcp数据迁移 编辑:程序博客网 时间:2024/05/19 22:46

转自:http://blog.csdn.net/niushuai666/article/details/6413024

已知二叉树的先序遍历序列和中序遍历序列,求后序遍历序列。

 

先递归构造二叉树,然后递归得到后序序列。

 

思路:

 

先序序列的第一个结点为要构造二叉树的根结点,在中序序列中查找二叉树的根结点,则中序列根结点左边为根结点的左子树的中序序列,右边为根结点的右子树的中序序列。而先序序列根结点后面分别为它的左子树和右子树的先序序列。有了根结点在中序序列的位置,就知道了左子树和右子树的先序序列各自的位置。这样,就知道了根结点两个子树的序列。

然后在构造了根结点后,就可以递归调用函数来勾结根结点的左子树和右子树。

 

以上为二叉树的恢复。

 

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

 

代码如下:

 

string.find()   返回查找元素的下标

string.substr(a, b)   从第a个下标的元素开始截取b个元素 

 代码如下:


#include<iostream>#include<cstdio>#include<string>using namespace std;struct Node{char data;Node * lchild;Node * rchild;};Node* CreatTree(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 = CreatTree(pre.substr(1, index), in.substr(0, index));  //递归创建左子树root->rchild = CreatTree(pre.substr(index + 1), in.substr(index + 1)); //递归创建右子树}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;Node *root;while(cin>>pre_str>>in_str){root = CreatTree(pre_str, in_str);PostOrder(root);cout<<endl;}return 0;}        


0 0