给定一个数组,将数组的值按层序构造一棵二叉树c语言
时间: 2023-09-17 09:13:38 浏览: 101
下面是按照层序构造一棵二叉树的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
typedef struct QueueNode {
TreeNode* node;
struct QueueNode* next;
} QueueNode;
typedef struct {
QueueNode* front;
QueueNode* rear;
} Queue;
Queue* createQueue() {
Queue* queue = (Queue*)malloc(sizeof(Queue));
queue->front = NULL;
queue->rear = NULL;
return queue;
}
int isEmpty(Queue* queue) {
return queue->front == NULL;
}
void enqueue(Queue* queue, TreeNode* node) {
QueueNode* queueNode = (QueueNode*)malloc(sizeof(QueueNode));
queueNode->node = node;
queueNode->next = NULL;
if (isEmpty(queue)) {
queue->front = queueNode;
queue->rear = queueNode;
} else {
queue->rear->next = queueNode;
queue->rear = queueNode;
}
}
TreeNode* dequeue(Queue* queue) {
if (isEmpty(queue)) {
return NULL;
}
QueueNode* front = queue->front;
TreeNode* node = front->node;
queue->front = front->next;
free(front);
if (queue->front == NULL) {
queue->rear = NULL;
}
return node;
}
TreeNode* buildTree(int* arr, int arrSize) {
if (arrSize == 0) {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = arr[0];
root->left = NULL;
root->right = NULL;
Queue* queue = createQueue();
enqueue(queue, root);
int i = 1;
while (!isEmpty(queue)) {
TreeNode* curNode = dequeue(queue);
if (i < arrSize && arr[i] != NULL) {
curNode->left = (TreeNode*)malloc(sizeof(TreeNode));
curNode->left->val = arr[i];
curNode->left->left = NULL;
curNode->left->right = NULL;
enqueue(queue, curNode->left);
}
i++;
if (i < arrSize && arr[i] != NULL) {
curNode->right = (TreeNode*)malloc(sizeof(TreeNode));
curNode->right->val = arr[i];
curNode->right->left = NULL;
curNode->right->right = NULL;
enqueue(queue, curNode->right);
}
i++;
}
return root;
}
void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
int main() {
int arr[] = {1, 2, 3, 4, NULL, 5, 6, NULL, NULL, 7, NULL, NULL, NULL, NULL, NULL};
int arrSize = sizeof(arr) / sizeof(int);
TreeNode* root = buildTree(arr, arrSize);
inorderTraversal(root); // 输出:4 2 5 1 6 3 7
return 0;
}
```
这个C语言程序可以根据输入的数组构造出一棵二叉树,并输出中序遍历结果。
阅读全文