0
点赞
收藏
分享

微信扫一扫

1066. 还原二叉树

eelq 2022-02-12 阅读 53

题目:
在这里插入图片描述
样例:
input:
9
ABDFGHIEC
FDHGIBEAC
output:
5
思路:
前序遍历:根节点->左节点->右节点
中序遍历:左节点->根节点->右节点
前序遍历的第一个必然是根节点,接着可以在中序遍历里找到这个根节点,随之确定右节点。
代码:

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#define maxn 1111
using namespace std;
char pre[maxn],med[maxn];
int n;
int dfs(char *pre,char *med,int n)
{
    if(n==0) return 0;
    int temp;
    for(int i=0;i<n;i++)
    {
        if(med[i]==pre[0]) temp=i;
    }
    int left=dfs(pre+1,med,temp);
    int right=dfs(pre+temp+1,med+temp+1,n-temp-1);
    return max(left,right)+1;
}
int main()
{
    cin>>n>>pre>>med;
    int ans=dfs(pre,med,n);
    cout<<ans<<endl;
    return 0;
}
举报

相关推荐

0 条评论