PAT : 数据结构与算法题目集(中文)7-23 还原二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/belous_zxy/article/details/87862239
#include <array>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class BinTreeString
{
  public:
    int buildtree(int, int, int = 0, int = 0, int = 1) const;
    BinTreeString(void)
    {
        cin >> str1 >> str2;
    };

  private:
    string str1, str2;
    const int ERROR{-1};
};
int BinTreeString::buildtree(int str1end, int str2end, int str1beg, int str2beg, int high) const
{
    if (str1beg > str1end || str2beg > str2end)
        return high - 1;
    if (str1beg == str1end)
        return high;
    for (auto i = str2beg; i <= str2end; ++i)
    {
        if (str2[i] == str1[str1beg])
            return max(buildtree(str1end - (str2end - i), i - 1, str1beg + 1, str2beg, high + 1),
                       buildtree(str1end, str2end, str1end - (str2end - i) + 1, i + 1, high + 1));
    }
    return ERROR;
}
int main(int argc, char *argv[])
{
    int cnt;
    cin >> cnt;
    BinTreeString A;
    cout << A.buildtree(cnt - 1, cnt - 1) << endl;
    return EXIT_SUCCESS;
}

以先序遍历为目标,递归查找中序遍历中的根节点,得到树节点中最大高度。

最近学了一点C++11,就试着用类写的。

END

猜你喜欢

转载自blog.csdn.net/belous_zxy/article/details/87862239
今日推荐