zoukankan      html  css  js  c++  java
  • 二叉树遍历

     题目截图:

    思路:

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

    代码如下:

     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("
    ");
    61     } 
    62     
    63     return 0;
    64 }
  • 相关阅读:
    jmeter压力测试报错:java.net.BindException: Address already in use: connect
    C# 对话框总结(转载)
    C# 文件操作方法大全(转载)
    C#实现进度条progress control(转载)
    在Windows下架设FTP服务器
    .Net环境下,使用installutil.exe注册、删除windows服务
    用双网卡实现跨网段访问(转载)
    HTTP协议详解(转载)
    学习开发web服务(转载)
    C# 实现http协议的GET和POST请求(转载)
  • 原文地址:https://www.cnblogs.com/coderJiebao/p/HustTest09.html
Copyright © 2011-2022 走看看