c语言一个字符串,根据输入的字符串建立二叉树
时间: 2023-11-27 08:43:53 浏览: 151
c语言构建二叉树
好的,建立二叉树的过程可以分为两步:先将字符串转换为二叉树的先序遍历序列,再根据先序遍历序列构建二叉树。具体实现如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct TreeNode {
char val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 将字符串转换为二叉树的先序遍历序列
void str2preorder(char *str, char *preorder, int *index) {
if (*str == '\0') {
return;
}
preorder[(*index)++] = *str;
if (*str != '#') {
str2preorder(str + 1, preorder, index);
str2preorder(str + 2, preorder, index);
}
}
// 根据先序遍历序列构建二叉树
TreeNode* buildTree(char *preorder, int *index) {
if (preorder[*index] == '#') {
(*index)++;
return NULL;
}
TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = preorder[(*index)++];
node->left = buildTree(preorder, index);
node->right = buildTree(preorder, index);
return node;
}
int main() {
char str[100], preorder[100];
int index = 0;
printf("请输入字符串:");
scanf("%s", str);
str2preorder(str, preorder, &index);
preorder[index] = '\0';
index = 0;
TreeNode *root = buildTree(preorder, &index);
return 0;
}
```
阅读全文