1:
输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。
第一行输入二叉树的先序遍历序列;
第二行输入二叉树的中序遍历序列。
输出该二叉树的后序遍历序列。
ABDCEF
BDAECF
DBEFCA
代码:
#include <iostream>
#include<cstdio>
#include<cstring>
using namespace std;
char pre_name[100];
char in_name[100];
struct Node
{
    char ch;
    Node *lefted,*righted;
    Node():ch(0),lefted(NULL),righted(NULL) {}
};
Node *Root;
Node *build(int L1,int R1,int L2,int R2)//前序找根,中序分割建树
{
    if(L2>R2)return NULL;
    Node *root;
    root=new Node();
    root->ch=pre_name[L1];
    int p=L2;
    while(in_name[p]!=root->ch)p++;
    int cnt=p-L2;
    root->lefted=build(L1+1,L1+cnt,L2,p-1);
    root->righted=build(L1+cnt+1,R1,p+1,R2);
    return root;
}
void select_post(Node *tree)
{
    if(tree)
    {
        select_post(tree->lefted);
        select_post(tree->righted);
        cout<<tree->ch;
    }
}
int main()
{
    scanf("%s%s",pre_name,in_name);
    int n=strlen(pre_name);
    Root=build(0,n-1,0,n-1);
    select_post(Root);
    cout<<endl;
    return 0;
}
 
 
                    
                     
                    
                 
                    
                 

 
         
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号