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

hdu 1710 二叉树的遍历

时间:2015-03-27 21:54:23      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:

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

大意:给出一个二叉树的前序和中序,求其后序遍历

 

ps:1.在写链表时,需要写明typedef struct node{};即声明一个指向自己的数据类型,而不是直接写struct node{}

      2.采用分治的思想,把一颗二叉树分解成n棵二叉树,每棵都有其对应的根节点,利用这点进行遍历

      3.malloc在#include<stdlib.h>头文件中

      4.这是自己第一次写数据结构树型题目,所以代码是借鉴而来的

 

 1 #include<iostream>
 2 #include<stdio.h>
 3 #include<stdlib.h>
 4 
 5 using namespace std;
 6 
 7 typedef struct node{
 8     node *l,*r;
 9     int num;
10 }tree;
11 
12 tree *root;
13 
14 tree *creat(int *a,int *b,int n){
15     tree *t;
16     for(int i=0;i<n;i++){
17         if(a[0] == b[i]){//找到根节点
18             t = (tree *)malloc(sizeof(tree));
19             t->num = b[i];
20             t->l = creat(a+1,b,i);
21             t->r = creat(a+i+1,b+i+1,n-i-1);
22             return t;
23         }
24     }
25     return NULL;
26 }
27 
28 void houxu(tree *h){
29     if(h!=NULL){
30         houxu(h->l);
31         houxu(h->r);
32         if(h == root)
33             cout<<h->num<<endl;  //最后是根节点
34         else
35             cout<<h->num<<" ";
36     }
37     return ;
38 }
39 
40 int main(){
41     int n;
42     int a[1005],b[1005];
43     while(cin>>n){
44         for(int i=0;i<n;i++)
45             scanf("%d",a+i);
46         for(int i=0;i<n;i++)
47             scanf("%d",b+i);
48         root = creat(a,b,n);
49         tree *h = root;
50         houxu(h);
51     }
52     return 0;
53 }

 

hdu 1710 二叉树的遍历

标签:

原文地址:http://www.cnblogs.com/pngcui/p/4372928.html

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