根据二叉树的先序遍历和中序遍历还原二叉树并且求二叉树的高度

#include<iostream>
#include<string>
using namespace std;
string s1, s2;
class Tree
{
public:
    char c;
    Tree *left;
    Tree *right;
};
Tree* create()
{
    Tree *p = new Tree;
    p->left = p->right = NULL;
    return p;
}


Tree* huanyuan(int x1, int x2, int y1, int y2)
{
    Tree *t = create();

    t->c = s1[x1];
    for (int j = y1; j <= y2; j++)
    {
        if (s1[x1] == s2[j])
        {
            if (j != y1)
                t->left = huanyuan(x1 + 1, x1 + j - y1, y1, j - 1);
            if (j != y2)
                t->right = huanyuan(x1 + j - y1 + 1, x2, j + 1, y2);
            break;
        }
    }
    return t;
}
int shendu(Tree *t)
{
    if (t == NULL)
        return 0;
    int m = shendu(t->left);
    int n = shendu(t->right);
    if (m > n)
        return m + 1;
    else
        return n + 1;
}
int main()
{
    int n;
    cin >> n;
    cin >> s1 >> s2;
    Tree *t = huanyuan(0, s1.size() - 1, 0, s2.size() - 1);
    cout << shendu(t);
}

猜你喜欢

转载自www.cnblogs.com/x-huihui/p/9809873.html