On request] [tree preorder

Original title Portal

topic


Title Description

Given a binary sequence in the subsequent order. Arranged in order to obtain it. (Tree node agreement with different capital letters).

Input and output formats

Input format:
string line 2, both capital letters represents sequence to the sequence arranged in a binary tree.
Output format:
1 line, represents a first binary sequence a.

Thinking


First, a little common sense, give you a post-order traversal, then the last one is the root (such as ABCD, the root is D).
Because the subject of the first order seeking means to continue to look for the root.
In order ACGDBHZKX, subsequent CDGAHXKZB, first find the main root B;
we find inorder traversal from B, by the nature of the traversal, inorder traversal may be divided into two ACGD and HZKX subtree,
then find the corresponding post preorder CDGA and HXKZ (de novo can find)
so the question becomes preorder ACGD rEQUIREMENTS 1., 2. tree in order CDGA postorder traversal HZKX, HXKZ postorder traversal of the tree;
then recursively, according to the original method , find the sub-root 1. A, sub-divided into two sub-tree root 2. Z, subdivided into two sub-trees.
Click this have to do so (the first output root, recursively);
template summarized as step1: find root and output
step2: will be in sequence, after each divided into about two subtrees;
step3: recursion, repeat step1,2;

Code


#include<cstdio>
#include<iostream>
#include<cstring>
using namespace std;
void beford(string in,string after){
    if (in.size()>0){
        char ch=after[after.size()-1];
        cout<<ch;//找根输出
        int k=in.find(ch);
        beford(in.substr(0,k),after.substr(0,k));
        beford(in.substr(k+1),after.substr(k,in.size()-k-1));//递归左右子树;
    }
}
int main(){
    string inord,aftord;
    cin>>inord;cin>>aftord;//读入
    beford(inord,aftord);cout<<endl;
    return 0;
}

Guess you like

Origin www.cnblogs.com/gongdakai/p/11066351.html