And it is known in preorder traversal order request postorder

  And a sequence preorder traversal of a tree as follows:

Preorder: ABCDEFGHI

Postorder: CEDFBAHGI

Postorder results: EFDCBHIGA

First, preorder process for the root - left - right, left traversing process - root - during and after the process of traversing the left - and right - root

Preorder traversal process apparent from the beginning of the root are first traversal, so that the tree can be divided by preorder traversal root corresponding to the root sequence preorder traversal.

Division results

Preorder traversal of the root: 

A B C D E F G H I

    

The following is a recursive solution process, pay attention to the process of each sub-interval represents a lesson sub-tree, in determining the position of the child to consider whether the tree roots have left subtree or subtree right subtree, for no special circumstances to be sentenced

#include<stdio.h>
#include<cstring>
#pragma warning(disable:4996)
#define maxn 100000
using namespace std;
char s1[maxn];
char s2[maxn];
void dfs(char root, int pos, int l, int r)
{
    if (r - l <= 1)
    {
        if(root != ' ')
        printf("%c", root);
        return;
    }
    for (int i = l; i < r; i++)
    {
        if (s2[i] == root)
        {
            char t = pos + 1 < strlen(s1)&&i !=l ? s1[pos + 1] : ' ';//i == l 没有左子树
            dfs(t, pos + 1, l, i);
            t = pos + 1 + i - l < strlen(s1)&&i!=r-1 ? s1[pos + 1 + i - l] : ' ';//i= r-1没有右子树
            dfs(t, pos + 1 + i - l, i+1, r);
            printf("%c", root);
        }
    }


}
int main()
{
    scanf("%s%s",s1,s2);
    int len1 = strlen(s1);
    int len2 = strlen(s2);
    char root = s1[0];
    dfs(root, 0, 0, len2);
    getchar();
    getchar();
    return 0;
}

 

 You are not brave, no one strong for you!

Guess you like

Origin www.cnblogs.com/zxzmnh/p/11567697.html