根据前序/后序/层序+中序遍历序列建立二叉树

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>

using namespace std;
const int N = 100;

typedef struct node
{
    char data;
    struct node *lchild, *rchild;
}Node, *Tree;

char pre[N], in[N], post[N];

void Pre_Build(Tree &root, int preL, int preR, int inL, int inR)
{
    if(preL > preR)
    {
        root = NULL;
        return;
    }
    root = new Node;
    root->data = pre[preL];
    int k;
    for(k = inL; k <= inR; k++)
        if(in[k] == pre[preL])
            break;
    int num = k - inL;
    Build(root->lchild, preL+1, preL+num, inL, k-1);
    Build(root->rchild, preL+num+1, preR, k+1, inR);
}

void In_Build(Tree &root, int inL, int inR, int postL, int postR)
{
    if(postL > postR)
    {
        root = NULL;
        return;
    }
    root = new Node;
    root->data = post[postR];
    int k;
    for(k = inL; k <= inR; k++)
        if(in[k] == post[postR])
            break;
    int num = k - inL;
    Build(root->lchild, inL, k-1, postL, postL+num-1);
    Build(root->rchild, k+1, inR, postL+num, postR-1);
}

void Layer_Build(Tree &root, vector<char> layer, int inL, int inR)
{
    if(layer.size() == 0)
    {
        root = NULL;
        return;
    }
    root = new Node;
    root->data = layer[0];
    int k;
    for(k = inL; k <= inR; k++)
        if(in[k] == layer[0])
            break;
    vector<char> layerL;
    vector<char> layerR;
    for(int i = 1; i < layer.size(); i++)
    {
        bool left = false;
        for(int j = 1; j < k; j++)
            if(in[j] == layer[i])
            {
                left = true;
                break;
            }
        if(left) layerL.push_back(layer[i]);
        else layerR.push_back(layer[i]);
    }
    Build(root->lchild, layerL, inL, k-1);
    Build(root->rhcild, layerR, k+1, inR);
}

已知前序或后序加上中序比较清晰简单,层序有点复杂,我没写出来,整理了一下,记住吧

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值