二叉树遍历问题

本文介绍了如何通过递归算法将二叉树的前序和中序遍历结果转换为后序遍历,以及如何从后序和中序遍历结果得出前序遍历。通过具体的C++代码实现,帮助读者理解二叉树遍历之间的转换过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前序中序求后序

代码:

#include <map>
#include <cmath>
#include <cstdio>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define met(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
const int maxn = 1e3+10;
char preorder[maxn],inorder[maxn];

void find(char *preorder,char *inorder,int len)
{
    if(len==0)
        return;
    char temp=*preorder;
    int rootindex=0;
    while(temp!=inorder[rootindex]&&rootindex<len)
        rootindex++;
    //    找到根节点。
    find(preorder+1,inorder,rootindex);//left
    find(preorder+rootindex+1,inorder+rootindex+1,len-rootindex-1);//right
    printf("%c",temp);
    return;
}

int main()
{
    scanf("%s%s",preorder,inorder);
    int len=strlen(preorder);
    find(preorder,inorder,len);
    printf("\n");
}

后序中序求前序

代码:

#include <map>
#include <cmath>
#include <cstdio>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define met(a,b) memset(a,b,sizeof(a))
#define inf 0x3f3f3f3f
const int maxn = 1e3+10;
char postorder[maxn],inorder[maxn];

void findpre(char *inorder,char *postorder,int len)
{
    if(len==0)
        return;
    char temp=postorder[len-1];
    int rootindex=len-1;
    while(temp!=inorder[rootindex]&&rootindex>=0)
        rootindex--;
    findpre(postorder,inorder,rootindex);//left
    findpre(postorder+rootindex,inorder+rootindex+1,len-rootindex-1);//right
    printf("%c",temp);
    return;
}

int main()
{
    scanf("%s%s",inorder,postorder);
    int len=strlen(postorder);
    findpre(inorder,postorder,len);
    printf("\n");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值