#include <stdio.h> #include <stdlib.h> typedef struct Node { char data; struct Node* leftNode; struct Node* rightNode; } Node; // 先序遍历拿到的是当前值,只需要左子树+1以及右子树+1 Node* create(Node* root, char str[], int* i) { char data = str[*i]; if (data == '#' || data == '\0') { root = NULL; return root; } else { root = (Node*)malloc(sizeof(Node)); root->data = data; (*i)++; root->leftNode = create(root->leftNode, str, i); (*i)++; root->rightNode = create(root->rightNode, str, i); return root; } } // 中序遍历 void LDR(Node* root) { if (root->leftNode != NULL) { LDR(root->leftNode); } printf("%c ", root->data); if (root->rightNode != NULL) { LDR(root->rightNode); } } int main() { Node* root;//定义一个根节点指针 root = NULL;//将根节点指针赋值为空 char str[100] = {0}; int i = 0; scanf("%s", str); root = create(root, str, &i);//构建树 LDR(root); return 0; }