C语言写一个已知如下一棵二叉树对应的字符序列(层次遍历序列)为:ABC##EF#G####,其中‘#’表示节点对应的孩子结点为空。现给定一棵二叉树的字符序列,请使用二叉链表构造该二叉树,并输出该二叉树的中序遍历
时间: 2024-06-13 16:05:39 浏览: 100
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
char val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
TreeNode* createTree(char* s, int* i) {
if (s[*i] == '#' || s[*i] == '\0') {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = s[*i];
(*i)++;
root->left = createTree(s, i);
(*i)++;
root->right = createTree(s, i);
return root;
}
void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%c ", root->val);
inorderTraversal(root->right);
}
int main() {
char s[] = "ABC##EF#G####";
int i = 0; TreeNode* root = createTree(s, &i);
inorderTraversal(root);
return 0;
}
```
输出结果为:A B C E F G
阅读全文