#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAX 101typedef struct…
- User
#include <stdio.h>#include <stdlib.h>#include <string.h>#define MAX 101typedef struct TreeNode { char val[4]; struct TreeNode* lchild; struct TreeNode* rchild;} TreeNode;TreeNode* CreatTree(char** tokens, int* index) { if (strcmp(tokens[index], “#”) == 0) { (index)++; return NULL; } TreeNode node = (TreeNode)malloc(sizeof(TreeNode)); strcpy(node->val, tokens[index]); (index)++; node->lchild = CreatTree(tokens, index); node->rchild = CreatTree(tokens, index); return node;}void Print(TreeNode root) { if (!root) return; if (root->lchild && root->rchild) { printf(“(”); } Print(root->lchild); printf(“%s”,root->val); Print(root->rchild); if (root->lchild && root->rchild)printf(“)”);}int main() { char c[MAX+1]; while (fgets(c, 100, stdin)) { char tokens[51]; char* token = strtok(c, " \n"); int count = 0; while (token) { tokens[count++] = token; token = strtok(NULL, " \n"); } int index = 0; TreeNode* T = CreatTree(tokens, &index); Print(T); printf(“\n”); } return 0;}在这个代码的基础上,添加代码,使其在表达式后输出表达式的结果
- Assistant
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> // 添加此头文件 #define MAX 101
typedef struct TreeNode { char val[4]; struct TreeNode* lchild; struct TreeNode* rchild; } TreeNode;
TreeNode* CreatTree(char** tokens, int* index) { if (strcmp(tokens[index], "#") == 0) { (index)++; return NULL; } TreeNode node = (TreeNode)malloc(sizeof(TreeNode)); // 修改此处 strcpy(node->val, tokens[*index]); // 修改此处 (*index)++; node->lchild = CreatTree(tokens, index); node->rchild = CreatTree(tokens, index); return node; }