已知前序中序求后序-二叉树

writer:pprp

思路很容易理解,但是实现还是有一点难度,容易错

参考书目:《算法竞赛宝典》

代码如下:

//已知前序中序,求后序
#include <iostream>

using namespace std;

//a是前序,b是中序
void hwg(string a,string b)
{
    int ll,lr;

    for(unsigned int i = 0; i < b.length(); i++)
    {
        if(a[0] == b[i])    //找到根节点
        {
            ll = i;                   //分别计算出左右子树的长度
            lr = b.length()-1-ll;
            if(ll)                     //
            {
                string part1(a,1,ll),part2(b,0,11);
                hwg(part1,part2);
            }
            if(lr)
            {
                string part3(a,1+ll,lr),part4(b,1+ll,lr);
                hwg(part3,part4);
            }
            cout << a[0];
            break;
        }
    }
}

int main()
{
    string a,b;
    cout <<"请输入前序:"<<endl;
    cin >> a;
    cout <<"请输入中序:"<<endl;
    cin >> b;
    cout <<"后序为:"<<endl;
    hwg(a,b);
    return 0;
}

 

posted @ 2017-07-22 11:00  pprp  阅读(369)  评论(0编辑  收藏  举报