题解 | #二叉树遍历#

二叉树遍历

https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef

#include <stdio.h>
#include<stdlib.h>
#include<string.h>

typedef char DataType;
typedef struct tree
{
    DataType val;
    struct tree* left;
    struct tree* right;
}Tree;

Tree* TreeCreate(Tree** root, DataType* a, int* pi)
{
    if (a[*pi] == '#')
    {
        (*pi)++;
        return NULL;
    }
    Tree* temp = (Tree*)malloc(sizeof(Tree));
    if (temp == NULL)
    {
        perror("malloc fail");
        exit(-1);
    }
    *root = temp;
    (*root)->val = a[(*pi)++];
    (*root)->left = NULL;
    (*root)->right = NULL;
    (*root)->left = TreeCreate(&(*root)->left, a, pi);
    (*root)->right = TreeCreate(&(*root)->right, a, pi);
    return *root;
}

void middle_order(Tree* root, DataType** str, int* size, int n)
{
    if (root == NULL || *size >= n)
    {
        return;
    }
    middle_order(root->left, str, size, n);
    (*str)[(*size)++] = root->val;
    middle_order(root->right, str, size, n);
}

int main() {
    DataType a[100];
    scanf("%s", a);
    int pi = 0;
    int n = strlen(a);
    Tree* root = TreeCreate(&root, a, &pi);
    DataType* str = (DataType*)malloc(n * sizeof(DataType));
    int size;
    middle_order(root, &str, &size, n);
    for (int i = 0; i < size; i++) {
        printf("%c ", str[i]);
    }
    free(str); 
    return 0;
}

全部评论

相关推荐

头像
不愿透露姓名的神秘牛友
05-27 11:41
已编辑
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务