hdu 1710 Binary Tree Traversals

系统 1602 0

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 590    Accepted Submission(s): 241


   本题如果学过数据结构的话,应该问题不大,就是给一个先序遍历,一个中序遍历,求后序遍历,一般我们做的时候就是根据先序遍历和中序遍历建造一个树,然后再对这个树进行后序遍历输出就行了。后序遍历树很简单,我们就不多说了,关键是怎样建树。首先我们应该搞清楚先序遍历和中序遍历,在中序遍历中如果这个数出现在某个节点的前面就表明此数在这个节点的左边,如果这个数出现在某个节点的后面就表明此数出现在这个节点的右边。
代码:

 

      
1 #include < stdio.h >
2 #include < stdlib.h >
3   int n,pre[ 1005 ], in [ 1005 ];
4 typedef struct node
5 {
6 int data;
7 int index;
8 struct node * Lchild, * Rchild;
9 }bitree, * Tree;
10   void dfs(Tree & root, int index)
11 {
12 if (root == NULL)
13 {
14 root = (Tree)malloc( sizeof (bitree));
15 root -> data = in [index];
16 root -> index = index;
17 root -> Lchild = NULL;
18 root -> Rchild = NULL;
19 return ;
20 }
21 else
22 {
23 if (index < root -> index)
24 dfs(root -> Lchild,index);
25 else
26 dfs(root -> Rchild,index);
27 }
28 }
29 void createbitree(Tree & root)
30 {
31 int i,j,index;
32 root = (Tree)malloc( sizeof (bitree));
33 for (i = 1 ;i <= n;i ++ )
34 if ( in [i] == pre[ 1 ])
35 {
36 root -> data = pre[ 1 ];
37 root -> index = i;
38 root -> Lchild = NULL;
39 root -> Rchild = NULL;
40 break ;
41 }
42 index = i;
43 for (i = 2 ;i <= n;i ++ )
44 for (j = 1 ;j <= n;j ++ )
45 if ( in [j] == pre[i])
46 {
47 if (j < index)
48 dfs(root -> Lchild,j);
49 else
50 dfs(root -> Rchild,j);
51 break ;
52 }
53 }
54 void post(Tree root, int x)
55 {
56 if (root == NULL)
57 return ;
58 post(root -> Lchild,x + 1 );
59 post(root -> Rchild,x + 1 );
60 if (x == 0 )
61 printf( " %d " ,root -> data);
62 else
63 printf( " %d " ,root -> data);
64 }
65 int main()
66 {
67 int i;
68 while (scanf( " %d " , & n) != EOF)
69 {
70 Tree root;
71 for (i = 1 ;i <= n;i ++ )
72 scanf( " %d " , & pre[i]);
73 for (i = 1 ;i <= n;i ++ )
74 scanf( " %d " , & in [i]);
75 createbitree(root);
76 post(root, 0 );
77 printf( " \n " );
78 }
79 return 0 ;
80 }
81

 

hdu 1710 Binary Tree Traversals


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论