题解 | #二叉树遍历#
二叉树遍历
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; }