PATA1086_二叉树(难度:⭐️⭐️)

这篇博客介绍了如何通过前序遍历和中序遍历的序列来构建二叉树。代码实现了一个从输入序列构建二叉树的函数,并通过后序遍历来验证构建结果。主要内容涉及二叉树的遍历和构造算法。

就是前序中序建树。

//9:26 ~
#include<bits/stdc++.h>
using namespace std;
vector<int> pre, in, ans;
int st[31], pos = -1;
struct node {
    int val;
    node *lc, *rc;
};
node *bulid (int preL, int preR, int inL, int inR) {
    if (preL > preR) return NULL;
    node *root = new node();
    root->val = pre[preL];
    int k = inL;
    while (in[k] != pre[preL]) k++;
    int left = k - inL;
    root->lc = bulid (preL + 1, preL + left, inL, k - 1);
    root->rc = bulid (preL + left + 1, preR, k + 1, inR);
    return root;
}
void post(node *root) {
    if (root == NULL) return;
    post(root->lc);
    post(root->rc);
    ans.push_back(root->val);
}
int main() {
    int n, a;
    string s;
    cin >> n;
    for (int i = 0; i < 2 * n; i++) {
        cin >> s;
        if (s == "Pop") {
            in.push_back(st[pos--]);
            continue;
        }
        else {
            cin >> a;
            pre.push_back(a);
            st[++pos] = a;
        }
    }
    node *root = NULL;
    root = bulid (0, n - 1, 0, n - 1);
    post(root);
    for (int i = 0; i < ans.size(); i++) {
        if (i != 0) printf (" ");
        printf ("%d", ans[i]);
    }
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值