输入一棵二叉树的先序和中序遍历序列,输出其后序遍历序列

描述
输入一棵二叉树的先序和中序遍历序列,输出其后序遍历序列。
输入
输入文件为tree.in,共两行,第一行一个字符串,表示树的先序遍历,第二行一个字符串,表示树的中序遍历。树的结点一律用小写字母表示。
输出
输出文件为tree.out,仅一行,表示树的后序遍历序列。
样例输入
abdec
dbeanc
样例输出
debca


// 思路:
// 前序序列的第一个值是根节点,将中序序列分成两部分。左边是左子树,右边是右子树
// 在左子树中,对应的前序序列的第二,是左子树的根节点,左边是其左子树,右边是其右子树
// 在右子树中,同理
// 当左子树为空,右子树为空时,结束

 #include<bits/stdc++.h>
using namespace std;
const int N = 1000;
struct Node
{
    char data;
    Node *lChild, *rChild;
};

void postOrder(Node *root)
{
    if (root == nullptr)
        return;

    postOrder(root->lChild);
    postOrder(root->rChild);
    cout << root->data;
}
//寻找中序序列中的下标
int search(int num, char *in, int len)
{

    for (int i = 0; i < len; i++)
        if (in[i] == num)
            return i;
    return -1;
}
Node *msn(char *pre, char *in, int len)
{
    if (len <= 0)
        return NULL;
    Node *root;
    root = new Node;
    int index = search(*pre, in, len);
    root->data = *pre;
    root->lChild = msn(pre + 1, in, index);
    // root->lChild=msn(pre+1,in,index);
    root->rChild = msn(pre + index + 1, in + index + 1, len - index - 1);
    // root->rChild=msn(pre+index+1,in,len-index-1);
    return root;
}
int main()
{
    char *pre, *in;
    pre = new char[N];
    in = new char[N];
    cin >> pre;
    cin >> in;
    Node *root;
    root = msn(pre, in, strlen(in));
    postOrder(root);
    cout << endl;
}

发布了41 篇原创文章 · 获赞 5 · 访问量 2992

猜你喜欢

转载自blog.csdn.net/qq_43573743/article/details/103751662
今日推荐