根据中序和后序遍历序列求层序遍历序列

本文介绍了一种根据先序和中序遍历构建二叉树的方法,并实现了前序和层序遍历,同时还计算了树的高度。通过具体的代码示例展示了二叉树的构建过程及其遍历算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


如题,顺便还求了一下树的高度。

#include <iostream>
#include <queue>
#include <math.h>

using namespace std;

struct Node
{
    Node *lchild;
    Node *rchild;
    char c;
};

void preOrder(Node *T)
{
    cout << T->c;
    if (T->lchild != NULL)
    {
        preOrder(T->lchild);
    }
    if (T->rchild != NULL)
    {
        preOrder(T->rchild);
    }
}

void levelOrder(Node *T)
{
    queue<Node*> q;
    q.push(T);
    Node *temp;
    while (!q.empty())
    {
        temp = q.front();
        q.pop();
        cout << temp->c;
        if (temp->lchild != NULL)
        {
            q.push(temp->lchild);
        }
        if (temp->rchild != NULL)
        {
            q.push(temp->rchild);
        }
    }
}

Node Tree[100];
int local;
string str1,str2;

Node* creat()
{
    Tree[local].lchild = Tree[local].rchild = NULL;
    local++;
    return &Tree[local-1];
}

Node* build(int s1,int e1,int s2,int e2)
{
    Node *rec = creat();
    rec->c = str2[e2];
    int id = str1.find(str2[e2]);
    if (id != s1)
    {
        rec->lchild = build(s1,id-1,s2,s2+(id-s1)-1);
    }
    if (id != e1)
    {
        rec->rchild = build(id+1,e1,s2+(id-s1),e2-1);
    }
    return rec;
}

int find_high(Node *T)
{
    if (T == NULL) return 0;
    else
        return max(find_high(T->lchild),find_high(T->rchild))+1;
}

int main()
{
    cin >> str1 >> str2;
    local = 0;
    int len1 = str1.size();
    int len2 = str2.size();
    Node *T = NULL;
    T = build(0,len1-1,0,len2-1);
    preOrder(T);
    cout << endl;
    levelOrder(T);
    cout << endl;
    cout << find_high(T) << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值