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("
先序:");
    preVisit(T);
    printf("
中序:");
    midVisit(T);
    printf("
后序:");
    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@

输出如图:

经验分享 程序员 微信小程序 职场和发展