POJ 2255(二叉树问题)

本文详细介绍了如何通过递归方法解决二叉树前序遍历和中序遍历求后序遍历的问题。通过分析代码并运用string库中的find和substr函数,实现了一种高效且简洁的解决方案。

题意:根据前序遍历和中序遍历求后序遍历

结题报告:说真的,我对二叉树还是不太能理解,遇到这种题我就不会做,不过看了其他人写的代码,我慢慢的理解了大部分

(转载)递归求解,先根据先序找到根节点,再在中序中找到根节点,根据根节点再中序中的位置分别把先序和中序分成两个子树。(例如:DBACEGF ABCDEFG 第一次找到根节点为D,D在中序中第4个位置,分别把先序分成BAC和EGF,再把中序分成ABC和EFG)利用递归对其求解,得到整个树,再对其进行后序遍历即得到结果。

粘贴一下别人的代码:

#include <iostream>
#include <stdio.h>
#include <string>
using namespace std;
struct node
{
    char data;
    node *lchirld;
    node *rchirld;
};
node *create(string pre,string in)
{
    node *root;
    root=NULL;
    if(pre.length()>0)
    {
        root=new node;
        root->data=pre[0];
        int index=in.find(root->data);
        root->lchirld=create(pre.substr(1,index),in.substr(0,index));
        root->rchirld=create(pre.substr(index+1),in.substr(index+1));
    }
    return root;
}
void postorder(node *root)//原本用(node *&root),可是我不明白为什么,我去掉“&”时也AC了
{
    if(root!=NULL)
    {
        postorder(root->lchirld);
        postorder(root->rchirld);
        cout<<root->data;
    }
}
int main()
{
    string pre,in;
    while(cin>>pre>>in)
    {
        node *root;
        root=create(pre,in);
        postorder(root);
        cout<<endl;
    }
    return 0;
}
//_____(转载)

另外在本题中用到了string文件库的两个函数find()与substr();
具体解释如下:
是s.find(args)在S中查找args第一次出现的位置下标。而substr()有以下几种操作
1、s.substr(pos,n) 返回一个string类型的字符串,它包含s中从下标pos开始的n个字符。
2、s.substr(pos) 返回一个string类型的字符串,它包含从下标pos开始到s末尾的所有字符。
3.s.substr()返回s的副本。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值