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

HDU 1710

时间:2015-11-28 23:18:59      阅读:445      评论:0      收藏:0      [点我收藏+]

标签:

http://acm.hdu.edu.cn/showproblem.php?pid=1710

题意:给二叉树的先序遍历和中序遍历,确定后序遍历

解法:复习专业课找的一题,根据先序遍历和中序遍历建树,再对树做后序遍历

技术分享
#include <iostream>
#include <cstdio>

using namespace std;

struct Tree {
    Tree *lc, *rc;
    int data;
};

Tree *Create(int *preorder, int *inorder, int n) {
    for(int i = 0; i < n; i++) {
        if(preorder[0] == inorder[i]) {
            Tree *node = (Tree*)malloc(sizeof(Tree));
            node -> data = preorder[0];
            node -> lc = Create(preorder+1, inorder, i);
            node -> rc = Create(preorder+i+1, inorder+i+1, n-i-1);
            return node;
        }
    }
    return NULL;
}

int rt;

void PostOrder(Tree *root) {
    if(root != NULL) {
        PostOrder(root -> lc);
        PostOrder(root -> rc);
        if(root -> data == rt)
            printf("%d\n", root->data);
        else
            printf("%d ", root->data);
    }
}

Tree *root;
int preorder[1005], inorder[1005]; 

int main() {
    int n;
    while(~scanf("%d", &n)) {
        for(int i = 0; i < n; i++)
            scanf("%d", &preorder[i]);
        for(int i = 0; i < n; i++)
            scanf("%d", &inorder[i]);
        root = NULL;
        rt = preorder[0];
        root = Create(preorder, inorder, n);
        PostOrder(root);
    }
    return 0;
}
View Code

 

HDU 1710

标签:

原文地址:http://www.cnblogs.com/xiaohongmao/p/5003619.html

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