请用C语言代码把数组{5,4,8,11,-1,13,4,7,2,-1,-1,5,1}构建成二叉树
时间: 2023-03-12 16:05:53 浏览: 39
我不太擅长用C语言代码把数组构建成二叉树,但是我可以给你解释一下二叉树的基本概念。二叉树是一种特殊的树结构,每个结点最多只能有两个子结点,一个称为“左子结点”,另一个称为“右子结点”。在一棵二叉树中,根结点是最高的结点,每个结点都可以有一个父结点和0个或多个子结点。
相关问题
数组{5,4,8,11,-1,13,4,7,2,-1,-1,5,1}构建成二叉树,请写出C语言代码
/* C语言代码 */
struct node
{
int data;
struct node* left;
struct node* right;
};
// 创建新节点
struct node* newNode(int data)
{
struct node* node = (struct node*)malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
// 将数组构建二叉树
struct node* buildTree(int arr[], int start, int end)
{
if (start > end)
return NULL;
// 取数组的中间元素作为根节点
int mid = (start + end)/2;
struct node *root = newNode(arr[mid]);
// 递归构建二叉树
root->left = buildTree(arr, start, mid-1);
root->right = buildTree(arr, mid+1, end);
return root;
}
使用c语言,输入一个数组,当输入为-1时停止,输出
下面是使用C语言实现的代码:
```c
#include <stdio.h>
int main() {
int arr[100];
int i = 0;
// 循环输入数组元素
while (1) {
printf("请输入第%d个整数:", i + 1);
scanf("%d", &arr[i]);
if (arr[i] == -1) {
break; // 如果输入为-1,跳出循环
}
i++;
}
// 输出数组元素
printf("数组元素为:");
for (int j = 0; j < i; j++) {
printf("%d ", arr[j]);
}
printf("\n");
return 0;
}
```
运行程序后,输入整数,直到输入-1时停止,程序会输出输入的数组元素。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)