二叉树遍历

 题目截图:

 

思路:

  因为先序序列与中序序列可以确定一棵二叉树,因此先根据先序序列和后序序列建立二叉树,然后后序输出即可。详细讲解见另一篇博客

 

代码如下:

 1 /*
 2     二叉树遍历 
 3 */
 4 
 5 #include <stdio.h>
 6 #include <string.h>
 7 #include <math.h>
 8 #include <stdlib.h>
 9 #include <time.h>
10 #include <stdbool.h>
11 
12 #define N 26
13 char pre[N], in[N];    // 存储前序,中序遍历 
14 
15 // 二叉树存储结构 
16 typedef struct _node {
17     char data;                            // 数据域 
18     struct _node *lchild, *rchild;        // 左右子树 
19 } node;  
20 
21 // 根据先序序列和中序序列创建二叉树
22 // 先序序列[preL,preR],中序序列[inL,inR] 
23 node* create(int preL, int preR, int inL, int inR) {
24     if(preL > preR || inL > inR) {
25         return NULL;                    // 序列长度小于 0 则返回 
26     }
27     // 新建根结点 
28     node* root = (node*)malloc(sizeof(node));
29     root->data = pre[preL];                // 先序序列的第一个数即为根结点的数据域 
30     int k;
31     for(k=inL; k<=inR; ++k) {            // 在中序序列中寻找根结点 
32         if(in[k] == pre[preL]) {
33             break;
34         }
35     }
36     int numLeft = k-1-inL+1;            // 左子树结点个数
37     // 分别建立左子树和右子树 
38     root->lchild = create(preL+1, preL+numLeft, inL, k-1);
39     root->rchild = create(preL+numLeft+1, preR, k+1, inR);
40     return root;
41 } 
42 
43 // 后序遍历 
44 void postorder(node* root) {
45     if(root == NULL) {
46         return;
47     }
48     postorder(root->lchild);
49     postorder(root->rchild);
50     printf("%c", root->data);
51     free(root);
52 }
53 
54 int main() {
55     while(scanf("%s %s", pre, in) != EOF) {
56         node* root = NULL;
57         // 创建二叉树 
58         root = create(0, strlen(pre)-1, 0, strlen(in)-1);
59         postorder(root);                // 输出后序序列 
60         printf("\n");
61     } 
62     
63     return 0;
64 }

 

posted @ 2018-02-07 16:08  Just_for_Myself  阅读(294)  评论(0编辑  收藏  举报