后序遍历

20 篇文章 0 订阅

题目描述

已知某二叉树的先序序列和中序序列,编程计算并输出该二叉树的后序序列。

输入描述

有多组数据,每组分为两行输入,第一行表示指定二叉树的先序序列,第二行表示该二叉树的中序序列,序列元素均为大写英文字符,表示二叉树的结点。

输出描述

对于每组数组,在一行上输出该二叉树的后序序列。

输入

ABDGCEFH
DGBAECHF

输出

GDBEHFCA
#include<bits/stdc++.h>
using namespace std;

typedef struct Node {
    char data;
    struct Node *lchild;
    struct Node *rchild;
    Node(char ch) {
        data = ch;
        lchild = NULL;
        rchild = NULL;
    }
} Node;



void postOrder(Node *root) {
    if (root->lchild) postOrder(root->lchild);
    if (root->rchild) postOrder(root->rchild);
    cout << root->data;
}

Node *buildTree(string pre, string in) {
    int len = pre.length();
    if (len <= 0) return NULL;
    Node *root = new Node(pre[0]);
    int p = in.find(pre[0]);
    root->lchild = buildTree(pre.substr(1, p), in.substr(0, p));
    root->rchild = buildTree(pre.substr(p+1, len-p-1), in.substr(p+1, len-p-1));
    return root;
}

int main() {
    string in, pre;
    while (cin >> pre) {
        cin >> in;
        Node *root = buildTree(pre, in);
        postOrder(root);
        cout << endl;
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值