C语言根据层次输入创建二叉树

思想:

用一个数组接收层次输入(下标0不存储信息),看图可以发现父节点的左子树是自身下标乘以二,右子树是自身下标乘以二再加一。

A的下标是1,下标乘以二是左子树B的下标,下标乘以二再加一是有子树C的下标。

如果左子树或者右子树的下标对应的字符为‘*’,则当前为NULL,没有子树。

如果当前下标左子树下标大于数组长度(自身下标*2>数组长度),则当前没有左子树(为NULL)。

如果当前下标右子树下标大于数组长度(自身下标*2+1>数组长度),则当前没有右子树(为NULL)。

 

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include<stdbool.h>

// 创建树的数据类型
typedef struct Node {
    char val;
    struct Node* leftChild = NULL;
    struct Node* rightChild = NULL;
} Tree, * BiTree;

void preVisit(BiTree T);  // 先序遍历 
void midVisit(BiTree T);  // 中序遍历
void postVistit(BiTree T);// 后序遍历
void createTree(BiTree& T, int index);  // 用层次输入的数据。创建二叉树 
void inputData(BiTree& T);              // 输入树的层次遍历 

int main(void) {
    BiTree T;
    inputData(T);
    printf("\n先序:");
    preVisit(T);
    printf("\n中序:");
    midVisit(T);
    printf("\n后序:");
    postVistit(T);
}


char str[100];
int num = 1;
void createTree(BiTree& T, int index) {
    if (str[index] == '*') {
        T = NULL;
        return;
    }
    T = (BiTree)malloc(sizeof(Tree));
    T->val = str[index];
    T->leftChild = NULL;
    T->rightChild = NULL;
    if (index * 2 <= num) {
        createTree(T->leftChild, index * 2);
    }
    if (index * 2 + 1 <= num) {
        createTree(T->rightChild, index * 2 + 1);
    }
}
void inputData(BiTree& T) {
    char ch;
    while (1) {
        scanf("%c", &ch);
        if (ch == '@')
            break;
        str[num++] = ch;
    }
    num--;
    createTree(T, 1);
}

void preVisit(BiTree T) {
    if (T) {
        printf("%c", T->val);
        preVisit(T->leftChild);
        preVisit(T->rightChild);
    }
}
// 中序遍历
void midVisit(BiTree T) {
    if (T) {
        midVisit(T->leftChild);
        printf("%c", T->val);
        midVisit(T->rightChild);

    }
}
// 后序遍历
void postVistit(BiTree T) {
    if (T) {
        postVistit(T->leftChild);
        postVistit(T->rightChild);
        printf("%c", T->val);
    }
}

输入:abd*c*e@

输出如图:

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值