题解 | #二叉树遍历#
二叉树遍历
https://www.nowcoder.com/practice/4b91205483694f449f94c179883c1fef
#include <stdio.h> #include <stdlib.h> typedef char BTDataType; typedef struct BinaryTreeNode { BTDataType data; struct BinaryTreeNode* left; struct BinaryTreeNode* right; }BTNode; BTNode* BuyNode(BTDataType x) { BTNode* newnode = (BTNode*)malloc(sizeof(BTNode)); if (newnode == NULL) { perror("malloc fail"); return NULL; } newnode->data = x; newnode->left = NULL; newnode->right = NULL; return newnode; } BTNode* BinaryTreeCreatByString(char* arr, int* i) { if(arr[*i] == '#') { (*i)++; return NULL; } BTNode* root = BuyNode(arr[*i]); (*i)++; root->left = BinaryTreeCreatByString(arr, i); root->right = BinaryTreeCreatByString(arr, i); return root; } void InOrder(BTNode* root) { if (root == NULL) { //printf("# "); return; } InOrder(root->left); printf("%c ", root->data); InOrder(root->right); } int main() { char arr[100] = {0}; while(scanf("%s", arr) != EOF) { int i = 0; BTNode* root = BinaryTreeCreatByString(arr, &i); InOrder(root); printf("\n"); } return 0; }