输入层次遍历,输出中序,前序,后序遍历

题目描述

输入完全二叉树的层次遍历序列,输出该完全二叉树的中序遍历序列。

例如下面二叉树的层次遍历序列为“ABCDE",中序遍历为"DBEAC"。 

           A

         /    \

       B      C

     /    \

   D     E

遍历数采用递归写法,无需多说;而且前,中,后,皆为一法;

重要的是看怎么建立一个二叉树,且听分解;

//输入层次遍历输出中序

#include <cstdio>
#include <cstdlib>
#include <cstring>
//#define _OJ_
typedef struct tree1
{
    char data;
    struct tree1 *lchild;
    struct tree1 *rchild;
} tree1, *tree;

tree
creat_tree(tree T, char *str, int i, int len)
{
    if(2 * i <= len) {

    tree T1, T2;
    if((2 * i) <= len) {//左儿子
     T1 = (tree) malloc (sizeof(tree1));
     T1->data = str[2 * i];
     T->lchild = T1;
     T->lchild = creat_tree(T->lchild, str, 2 * i, len);
    }

    if((2 * i + 1) <= len) {//右儿子
     T2 = (tree) malloc (sizeof(tree1));
     T2->data = str[2 * i + 1];
     T->rchild = T2;
     T->rchild = creat_tree(T->rchild, str, 2 * i + 1, len);
     }

  }
    else//如果传入的数值大于len那么他就是叶子节点
       T->lchild = T->rchild = NULL;

    return T;
}

void
pre_oder(tree T)
{
    if(T != NULL)
    {
    pre_oder(T->lchild);
    printf("%c", T->data);
    pre_oder(T->rchild);
    }
}

int main(int argc, char const *argv[]) {
#ifndef _OJ_  //ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
#endif

    tree T;
    int i = 0, len = 0;
    char str[100];
    scanf("%s", str);

    len = strlen(str);//利用数组来存储完全二叉树那么左儿子为2i,右儿子为2i+1;
    for(i = len;i >= 0; i--)
    str[i + 1] = str[i];//0好不用,从一号开始
    T = (tree) malloc (sizeof(tree1));    T->data = str[1];
    T = creat_tree(T, str, 1, len);
    pre_oder(T);
    printf("\n");

    return 0;
}

 

转载于:https://www.cnblogs.com/airfand/p/4998907.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值