uva536 -- Tree Recovery

来源:互联网 发布:c语言对数函数怎么表示 编辑:程序博客网 时间:2024/06/06 02:07

题目在此

这一题是根据先序序列和中序序列建立二叉树,然后求后序序列。首先是输入问题,我采用stringstream来输入,然后递归建立二叉树,最后后序遍历二叉树,具体代码如下:

#include <iostream>#include <sstream>#include <string>#include <cstdio>using namespace std;struct Node{    char value;    Node* left;    Node* right;    Node():left(NULL),right(NULL){}};string preorder;    //先序序列string inorder;     //中序序列//preorder[L1,R1],inorder[L2,R2]Node* buildTree(int L1,int R1,int L2,int R2){    if(L2>R2)   //当中序序列的L2>R2时终止递归        return NULL;    Node* root=new Node();    root->value=preorder[L1];    int pos=0;    for(;pos<inorder.length();pos++)        if(inorder[pos]==preorder[L1])            break;    int cnt=pos-L2; //左子树结点个数    root->left=buildTree(L1+1,L1+cnt,L2,pos-1);    root->right=buildTree(L1+cnt+1,R1,pos+1,R2);    return root;}void postOrder(Node* root)  //后序遍历二叉树{    if(root==NULL)        return;    postOrder(root->left);    postOrder(root->right);    cout<<root->value;}int main(){    //freopen("test.txt","r",stdin);    string input;    while(getline(cin,input))   //输入    {        stringstream ss(input);        ss>>preorder>>inorder;        int len=preorder.length();        Node* root=buildTree(0,len-1,0,len-1);        postOrder(root);        cout<<endl;    }    return 0;}

做完这一题后,可以做uva548,这一题是根据后序序列和中序序列建立二叉树,然后再求解,两题在一起做效果最好。我的关于uva548的题解在此。

0 0