c语言中怎么输入来创建二叉树
时间: 2023-11-11 13:07:59 浏览: 40
在C语言中,可以使用结构体来定义二叉树节点,一般包括左右子树指针和节点值。可以通过递归的方式来创建二叉树。
以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* createBinaryTree() {
struct TreeNode *node = NULL;
int val;
scanf("%d", &val);
if (val != -1) {
node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = createBinaryTree();
node->right = createBinaryTree();
}
return node;
}
int main() {
struct TreeNode *root = NULL;
printf("请输入二叉树节点的值,-1表示空节点:\n");
root = createBinaryTree();
return 0;
}
```
在该代码中,`createBinaryTree()` 函数通过递归的方式创建二叉树,每次读入一个节点的值,如果为 -1,则表示该节点为空,返回 NULL。否则,创建一个新的节点,将节点值设为输入值,递归创建左右子树,并将左右子树的指针分别赋给新节点的 left 和 right 指针。
在主函数中,调用 `createBinaryTree()` 函数创建二叉树,并将根节点指针赋给变量 `root`。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)