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

题目1078:二叉树遍历(由前序遍历中序遍历得到后序遍历)

时间:2017-04-09 13:02:23      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:二叉树遍历   https   logs   bsp   .cpp   stream   turn   post   code   

题目链接:http://ac.jobdu.com/problem.php?pid=1078

 

题目详解:https://github.com/zpfbuaa/JobduInCPlusPlus

 

//
//  1078 二叉树遍历.cpp
//  Jobdu
//
//  Created by PengFei_Zheng on 09/04/2017.
//  Copyright © 2017 PengFei_Zheng. All rights reserved.
//
 
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string.h>
 
using namespace std;
 
struct Node{
    Node *lchild;
    Node *rchild;
    char c;
}tree[50];
 
int loc;
Node *creat(){
    tree[loc].lchild=tree[loc].rchild=NULL;
    return &tree[loc++];
}
 
char str1[30], str2[30];
void postOrder(Node *T){
    if(T->lchild!=NULL)
        postOrder(T->lchild);
    if(T->rchild!=NULL)
        postOrder(T->rchild);
    printf("%c",T->c);
}
 
Node *build(int s1, int e1, int s2, int e2){
    Node* ret = creat();
    ret->c=str1[s1];
    int rootIdx=0;
    for(int i = s2 ; i <=e2 ;  i++){
        if(str2[i] == str1[s1]){
            rootIdx=i;
            break;
        }
    }
    if(rootIdx!=s2){
        ret->lchild=build(s1+1, s1+(rootIdx-s2), s2, rootIdx-1);
    }
    if(rootIdx!=e2){
        ret->rchild=build(s1+(rootIdx-s2)+1, e1, rootIdx+1, e2);
    }
    return ret;
}
 
int main(){
    while(scanf("%s",str1)!=EOF){
        scanf("%s",str2);
        loc=0;
        int l1 = (int)strlen(str1);
        int l2 = (int)strlen(str2);
        Node* T = build(0,l1-1,0,l2-1);
        postOrder(T);
        printf("\n");
    }
    return 0;
}
 
/**************************************************************
    Problem: 1078
    User: zpfbuaa
    Language: C++
    Result: Accepted
    Time:0 ms
    Memory:1520 kb
****************************************************************/

 

题目1078:二叉树遍历(由前序遍历中序遍历得到后序遍历)

标签:二叉树遍历   https   logs   bsp   .cpp   stream   turn   post   code   

原文地址:http://www.cnblogs.com/zpfbuaa/p/6684057.html

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