算法训练 求先序排列 递归

题目链接

思路

在中序序列循环一遍找到根节点,根节点其实就是后序遍历的最后一个节点。这样就将中序遍历划分为左右子树,在左右子树里面分别重复之前的操作。

code

#include <bits/stdc++.h>
using namespace std;
string in,post;
void preorder(int root,int st,int ed){
    if(st>ed) return;
    int i;
    for(i=st;i<=ed;i++) if(in[i]==post[root]) break;
    cout<<post[root];
    preorder(root-1-ed+i,st,i-1);//左子树
    preorder(root-1,i+1,ed);//右子树
}
int main(){
    cin>>in>>post;
    preorder((int)in.length()-1,0,(int)in.length()-1);
    return 0;
}

发布了83 篇原创文章 · 获赞 9 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43077261/article/details/103737141