(Recursive method) Do not build a binary tree model to solve the problem of "write out the post-order sequence according to the pre-order sequence and middle-order sequence"

(Recursive method) Do not build a binary tree model to solve the problem of "write out the post-order sequence according to the pre-order sequence and middle-order sequence"

Ideas

Insert picture description here
Search in the middle-order sequence through the sequence of the pre-order sequence, and use the characteristics of the middle-order sequence to divide and conquer to both sides, first divide and conquer the left and then divide and conquer the right, and finally output the root node;
this idea will have many repeated solutions, So we need to borrow the visited array to remove unnecessary duplicate solutions, and then we can get the output of the post-order sequence without building a binary tree.

Algorithm implementation

#include<iostream>
using namespace std;
#define N 100
//    1
//  2   3
//#  4 5 6
// 前序 1 2 4 3 5 6
// 中序 2 4 1 5 3 6
// 后序 4 2 5 6 3 1
/**
    辅助方法
    在序列中查找
    @param  int[]   序列
    @param  int     查询开始位置
    @param  int     查询结束位置
    @param  int     待查询元素
    @return int     查找到的元素的下标
*/
int search(int[],int,int,int);
/**
    根据前序和中序序列输出后序序列的递归方法
    @param  int     前序序列的长度
    @param  int[]   前序序列
    @param  int     遍历前序序列的开始位置
    @param  int[]   中序序列
    @param  int     中序序列递归开始位置
    @param  int     中序序列递归结束位置
*/
void postOrderSeq(int,int[],int,int[],int,int);

int visited[N]={
    
    0}; //防止重复访问

int main(){
    
    
    int preOrderSeq[N] = {
    
    1,2,4,3,5,6},inOrderSeq[N] = {
    
    2,4,1,5,3,6};
    int len = 6;
    postOrderSeq(len,preOrderSeq,0,inOrderSeq,0,len);
}

int search(int inOrderSeq[],int inStart,int inEnd,int x){
    
    
    for(int i = inStart;i < inEnd;i++)
        if(inOrderSeq[i] == x)return i;
    return -1;
}

void postOrderSeq(int len,int preOrderSeq[],int preStart,int inOrderSeq[],int inStart,int inEnd){
    
    
    for(int i = preStart;i < len;i++){
    
    
        int index = search(inOrderSeq,inStart,inEnd,preOrderSeq[i]);
        if(index != -1&&visited[index]!=1) {
    
    
            visited[index] = 1;
            postOrderSeq(len,preOrderSeq,i,inOrderSeq,0,index);
            postOrderSeq(len,preOrderSeq,i,inOrderSeq,index+1,inEnd);
            cout<<preOrderSeq[i]<<" ";
        }
    }
}

Insert picture description here

Recommended by other articles in this blog

The half-set problem of algorithm design and analysis

Record about the automatic initialization of C++ integer array to zero

Linear time selection for algorithm design and analysis

Divide and conquer strategy exercises for algorithm design and analysis (part 2)

Divide and conquer strategy exercises for algorithm design and analysis (on)

Divide and conquer strategy for algorithm design and analysis

Guess you like

Origin blog.csdn.net/L333333333/article/details/102871884