1086. Tree Traversals Again (25)

本文介绍了一种使用前序和中序遍历构建二叉树,并输出后序遍历结果的方法。通过读取输入创建二叉树节点,然后利用递归函数构建完整的树结构,最后进行后序遍历打印节点值。

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

//push是前序遍历 pop是中序遍历 根据前序遍历和中序遍历 输出后序遍历
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
int n;
vector<int> pre, in, post;
struct node { int data; node *l, *r; };
node *build(int preL, int preR, int inL, int inR){
    if(preL > preR) return NULL;
    node *root = new node;
    root->data = pre[preL];
    int k;
    for (k = inL; k <= inR; k++)
        if(in[k] == pre[preL]) break;
    int leftnum = k - inL;
    root->l = build(preL + 1, preL + leftnum, inL, k - 1);
    root->r = build(preL + leftnum + 1, preR, k + 1, inR);
    return root;
}
void postOrder(node *root){
    if (root == NULL) return;
    if(root->l) postOrder(root->l);
    if(root->r) postOrder(root->r);
    post.push_back(root->data);
}

int main(){
    cin >> n;
    stack<int> st;
    for (int i = 0; i < n * 2; i++) {
        string s;
        cin >> s;
        if (s == "Push") {
            int t;
            cin >> t;
            st.push(t);
            pre.push_back(t);
        }else{
            int t = st.top();
            st.pop();
            in.push_back(t);
        }
    }
    node *root = build(0, n - 1, 0, n - 1);
    postOrder(root);
    for (int i = 0; i < n; i++)
        printf("%d%c", post[i], i == n - 1 ? '\n' : ' ');

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值