4. 二叉树的创建及求解二叉树的宽度

【问题描述】求解二叉树的宽度,请用递归和非递归两种方法求解。

【输入形式】前序和中序序列建树

【输出形式】递归和非递归求解的宽度值

【样例输入】

abcdefg

cbdaegf

【样例输出】

3 3

#include <iostream>
using namespace std;
#include <cstring>
#include <queue>
struct node
{
    char data;
    node *lchild;
    node *rchild;
};
int height = 0;
int width[1000];
char mid[1001], pre[1001];
node *build(int x, int y, int q, int p) // xy为前序序列的左右边界,qp为前序序列的左右边界
{
    int i;
    if (x > y || q > p)
        return NULL;
    node *root = new node;
    root->data = pre[x];
    root->lchild = NULL;
    root->rchild = NULL;
    for (i = q; i <= p; i++)
        if (pre[x] == mid[i])
            break;
    root->lchild = build(x + 1, x + i - q, q, i - 1);
    root->rchild = build(x + i - q + 1, y, i + 1, p);
    return root;
}
void get_height(node *root, int step = 1)
{
    if (root == NULL)
        return;
    height = max(step, height);
    get_height(root->lchild, step + 1);
    get_height(root->rchild, step + 1);
}
void store_wild(node *root, int i) //递归方法
{
    if (root != NULL)
    {
        width[i]++;
        // cout << i << " " << width[i] << endl;
        store_wild(root->lchild, i + 1);
        store_wild(root->rchild, i + 1);
    }
}
int get_width1(node *root)
{

    get_height(root, 1);

    for (int i = 0; i < height; i++)
        width[i] = 0;
    store_wild(root, 0);
    // for (int i = 0; i < height; i++)
    //     cout << width[i];
    int maxx = 0;
    for (int i = 0; i < height; i++)
        maxx = max(maxx, width[i]);
    return maxx;
}
int get_width2(node *root)
{
    queue<node *> q;
    node *p = root;
    q.push(p);
    int maxx = 0;
    while (!q.empty())
    {
        int flag = 0;
        int len = q.size();
        while (flag < len)
        {
            flag++;
            p = q.front();
            q.pop();
            if (p->lchild)
                q.push(p->lchild);
            if (p->rchild)
                q.push(p->rchild);
        }
        maxx = max(maxx, len);
    }
    return maxx;
}
int main()
{
    cin >> pre >> mid;
    int len = strlen(mid);
    node *root;
    root = build(0, len - 1, 0, len - 1);
    cout << get_width1(root) << " " << get_width2(root);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wrong Ansewer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值