题解 | #二叉树遍历#

二叉树遍历

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;
}

全部评论

相关推荐

11-13 20:32
门头沟学院 Java
面向未来编程code:我没看到他咋急,他不就问你个问题。。。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务