用c语言写一个按层次遍历建立二叉树,并用先序遍历输出该二叉树
时间: 2023-03-26 17:03:37 浏览: 115
可以使用以下代码实现按层次遍历建立二叉树,并用先序遍历输出该二叉树:
```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 Queue {
QueueNode *front;
QueueNode *rear;
} Queue;
void initQueue(Queue *q) {
q->front = q->rear = NULL;
}
int isEmpty(Queue *q) {
return q->front == NULL;
}
void enqueue(Queue *q, TreeNode *node) {
QueueNode *newNode = (QueueNode *)malloc(sizeof(QueueNode));
newNode->node = node;
newNode->next = NULL;
if (isEmpty(q)) {
q->front = q->rear = newNode;
} else {
q->rear->next = newNode;
q->rear = newNode;
}
}
TreeNode *dequeue(Queue *q) {
if (isEmpty(q)) {
return NULL;
}
TreeNode *node = q->front->node;
QueueNode *temp = q->front;
q->front = q->front->next;
if (q->front == NULL) {
q->rear = NULL;
}
free(temp);
return node;
}
TreeNode *buildTree(int *nums, int size) {
if (size == ) {
return NULL;
}
TreeNode *root = (TreeNode *)malloc(sizeof(TreeNode));
root->val = nums[];
root->left = root->right = NULL;
Queue q;
initQueue(&q);
enqueue(&q, root);
int i = 1;
while (i < size) {
TreeNode *parent = dequeue(&q);
if (i < size && nums[i] != -1) {
TreeNode *left = (TreeNode *)malloc(sizeof(TreeNode));
left->val = nums[i];
left->left = left->right = NULL;
parent->left = left;
enqueue(&q, left);
}
i++;
if (i < size && nums[i] != -1) {
TreeNode *right = (TreeNode *)malloc(sizeof(TreeNode));
right->val = nums[i];
right->left = right->right = NULL;
parent->right = right;
enqueue(&q, right);
}
i++;
}
return root;
}
void preorderTraversal(TreeNode *root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
int main() {
int nums[] = {1, 2, 3, 4, 5, -1, 6, -1, -1, 7, 8};
int size = sizeof(nums) / sizeof(nums[]);
TreeNode *root = buildTree(nums, size);
preorderTraversal(root);
return ;
}
```
输出结果为:1 2 4 5 3 6 7 8
阅读全文