POJ 2255

本文详细介绍了二叉树的前序、中序和后序遍历方法,并提供了对应的代码实现。通过将所有节点视为根节点来还原二叉树结构,最终输出后序遍历结果。

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

题目大意:

二叉树,分别给出了前序遍历(根,左子树,右子树)与中序遍历(左子树,根,右子树),要求输出后序遍历(左子树,右子树,根)。

思路:

将所有节点全部看为根来做,先利用前、中序遍历还原二叉树原图,然后输出后序遍历。

 

代码:

#include<iostream>
#include<string>
using namespace std;
struct Tree
{
   char R;//元素
   Tree *lchild;//左子树指针
   Tree *rchild;//右子树指针
};

Tree *creatBit(string pre,string in)    //还原二叉树构造图
{
   Tree *root;
   int pos;
   if(pre.length()>0)
   {
       root=new Tree;
       root->R=pre[0];
       pos=in.find(root->R);
       root->lchild=creatBit(pre.substr(1,pos),in.substr(0,pos));
       root->rchild=creatBit(pre.substr(pos+1),in.substr(pos+1));
   }
   else root=NULL;
   return root;//返回的全部都是根。。。知道NULL为止
}

void postorder(Tree *root)   //后序遍历
{
   if(root!=NULL)
   {
       postorder(root->lchild);
       postorder(root->rchild);
       cout<<root->R;
   }
}

int main()
{
   Tree *root;
   string pre,in;
   while(!(cin>>pre>>in).eof())
   {
       root=creatBit(pre,in);
       postorder(root);
       cout<<endl;
   }
   return 0;
}

 

-------------------------------------------分割线-------------------------------------------------



下面这段代码仅方便理解该题使用,代码有局限性(CreateBiTree函数),自己看看就懂。

输入的是二叉树原图,输出分别为前、中、后序遍历。

注意:输入N个字母后,继续输入N+1个'&'再按回车。


代码:

#include<stdio.h>
#include<malloc.h>
typedef struct Node
{
   char data;
   struct Node*LChild;
   struct Node*RChild;
}BiTNode,*BiTree;
void CreateBiTree(BiTree *bt)
{
   char c;
   c=getchar();
   if(c=='&'*bt=NULL;
   else
   {*bt=(BiTree)malloc(sizeof(BiTNode));
   (*bt)->data=c;
   CreateBiTree(&((*bt)->LChild));
   CreateBiTree(&((*bt)->RChild));
   }
}
void PreOrder(BiTree bt)
{
   if(bt!=NULL)
   {
   printf("%c",bt->data);
   PreOrder(bt->LChild);
   PreOrder(bt->RChild);
   }
}
void InOrder(BiTree bt)
{
   if(bt!=NULL)
   {
       InOrder(bt->LChild);
       printf("%c",bt->data);
       InOrder(bt->RChild);
       
   }
}
void PostOrder(BiTree bt)
{
   if(bt!=NULL)
   {
       PostOrder(bt->LChild);
       PostOrder(bt->RChild);
       printf("%c",bt->data);
   }
}
void main()
{BiTNode*bt;
printf("请输入一个二叉树:\n");
CreateBiTree(&bt);
printf("请打印出先序遍历的结果是:\n");
PreOrder(bt);
printf("\n");
printf("请打印出中序遍历的结果是:\n");
InOrder(bt);
printf("\n");
printf("请打印出后序遍历的结果是:\n");
PostOrder(bt);
printf("\n");
}



二叉树遍历百度百科传送:http://baike.baidu.com/view/549587.htm



 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值