码迷,mamicode.com
首页 > 其他好文 > 详细

usaco American Heritage

时间:2015-09-28 08:44:39      阅读:187      评论:0      收藏:0      [点我收藏+]

标签:

给一颗二叉树的先序遍历,一个中序遍历,求输出后序遍历。

这是大一时候数据结构老师布置的课后作业,当时我记着这道题是我仅有的做错的题,老师还专门给我说过我的算法不合格。但是我后来并没有改正(因为懒)。

我的做法是将这个二叉树恢复出来,然后后序遍历。

当然可以不恢复出来直接搜,但我不觉着那样好写些,好多边界要处理。

/*
ID: modengd1
PROG: heritage
LANG: C++
*/
#include <iostream>
#include <stdio.h>
#include <memory.h>
#include <cstring>
#include <string.h>
using namespace std;
string inorder;
string preorder;
int N;
int a;
struct node
{
    string whole;
    int left;
    int right;
    char value;
};
node tree[27<<2];
void build(int root)
{
    if(tree[root].whole.size()==0)
        return;
    tree[root].value=preorder[a];
    a++;
    int b=tree[root].whole.find(tree[root].value);

    tree[root].left=N++;
    tree[root].right=N++;

    tree[tree[root].left].whole=tree[root].whole.substr(0,b);
    build(tree[root].left);

    tree[tree[root].right].whole=tree[root].whole.substr(b+1,tree[root].whole.size()-b);
    build(tree[root].right);
}
void output(int root)
{
    if(tree[root].whole.size()==0)
        return;
    output(tree[root].left);
    output(tree[root].right);
    printf("%c",tree[root].value);
}
int main()
{
    freopen("heritage.in","r",stdin);
    freopen("heritage.out","w",stdout);
    char ch;

    for(int i=0;scanf("%c",&ch)&&ch!=‘\n‘;i++)
        inorder.push_back(ch);

    for(int i=0;scanf("%c",&ch)&&ch!=‘\n‘;i++)
        preorder.push_back(ch);
    int root=1;
    tree[root].whole=inorder;
    tree[root].value=preorder[0];
    a=0;
    N=2;
    build(1);
    output(1);
    cout<<endl;
    return 0;
}

  

usaco American Heritage

标签:

原文地址:http://www.cnblogs.com/modengdubai/p/4843219.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!