• 博客园logo
  • 会员
  • 周边
  • 新闻
  • 博问
  • 闪存
  • 众包
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

cynchanpin

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

已知二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列

题目描写叙述
输入二叉树的先序遍历序列和中序遍历序列,输出该二叉树的后序遍历序列。
输入
第一行输入二叉树的先序遍历序列;
第二行输入二叉树的中序遍历序列。


输出
输出该二叉树的后序遍历序列。


演示样例输入
ABDCEF
BDAECF
演示样例输出
DBEFCA

#include <iostream>
#include <cstring>
#define MAX 50+3
using namespace std;
typedef char Elem_Type;
typedef struct BiTree
{
    Elem_Type data;//数据
    struct BiTree *Lchild;//左孩子
    struct BiTree *Rchild;//右孩子
}BiTree;      //要查找的元素  查找的地方    数组的长度
int Search_Num(Elem_Type num,Elem_Type *array,int len)
{
    for(int i=0; i<len; i++)
       if(array[i] == num)
         return i;
    //return -1;//没有找到
}                     //前序遍历         中序遍历   中序数组长度
BiTree *Resume_BiTree(Elem_Type *front,Elem_Type *center,int len)
{
    if(len <= 0)
      return NULL;
    BiTree *temp = new BiTree;
    temp->data = *front;
    int index = Search_Num(*front,center,len);
    temp->Lchild = Resume_BiTree(front+1,center,index);
    temp->Rchild = Resume_BiTree(front+index+1,center+index+1,len-index-1);
    return temp;
}
void PostOrderTraverse(BiTree *root)//后序遍历
{
    if( root != NULL)
    {
        PostOrderTraverse(root->Lchild);
        PostOrderTraverse(root->Rchild);
        cout<<root->data;
    }
}
int main(void)
{
    Elem_Type *preorder = new Elem_Type [MAX];//前序
    Elem_Type *inorder  = new Elem_Type [MAX];//中序
    cin>>preorder;cin>>inorder;
    BiTree *root = Resume_BiTree(preorder,inorder,strlen(inorder));
    PostOrderTraverse(root);
    cout<<endl;
    return 0;
}
/**************************************
	Problem id	: SDUT OJ 1291 
	User name	: 李俊 
	Result		: Accepted 
	Take Memory	: 444K 
	Take Time	: 0MS 
	Submit Time	: 2014-05-16 22:52:07  
**************************************/

posted on 2017-04-24 19:07  cynchanpin  阅读(803)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3