[Solution] ask questions after order traversal

Title Description

A binary input sequence and the first sequence preorder output sequence preorder thereafter.

Input and output formats

Input formats:

A total of two lines:
the first acts a string representing the preorder traversal of the tree;
second line a string representing the tree traversal order.
Tree nodes all lowercase letters.

Output formats:

Row represents the sequence postorder traversal of the tree.

Sample input and output

Sample input:

abdec
dbeac

Sample output:

debca

This question is a simple template title
first index index can set up a table to store the tree row which position each letter in the previous order traversal
may think:
first find out the root preorder traversal of the former, that is, index the minimum that a table
and then you can connect this tree to find out, is divided into two sub-tree
shown:
7491
recursively this practice on it!
With code:

#include<iostream>
#include<string>
using namespace std;
string pre,mid;
int index[127];
void dfs(int low,int high)
{
    if(low>high) return;
    int min=2147483647,root=0;
    for(register int i=low;i<=high;++i)
    {
        if(index[mid[i]]<=min)
        {
            min=index[mid[i]];
            root=i;
        }
    }
    dfs(low,root-1);
    dfs(root+1,high);
    cout<<mid[root];
}
int main()
{
    cin>>pre;
    cin>>mid;
    for(register int i=0;i<pre.size();++i) index[pre[i]]=i;
    dfs(0,pre.size()-1); 
}

Guess you like

Origin www.cnblogs.com/2021-yanghaoran/p/12010575.html