码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-10-18 14:04:05      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:char   tree   并且   ==   clu   中序遍历   string   class   public   

#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);
}

 

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

标签:char   tree   并且   ==   clu   中序遍历   string   class   public   

原文地址:https://www.cnblogs.com/x-huihui/p/9809873.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!