已知二叉树的先序序列,输出层序遍历序列。c语言数据结构代码
时间: 2023-12-08 14:35:53 浏览: 118
已知二叉树的先序序列,输出层序遍历序列的C语言代码如下:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct TreeNode {
char val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
typedef struct Queue {
TreeNode* data[MAX_SIZE];
int front;
int rear;
} Queue;
void initQueue(Queue* q) {
q->front = 0;
q->rear = 0;
}
int isEmpty(Queue* q) {
return q->front == q->rear;
}
int isFull(Queue* q) {
return (q->rear + 1) % MAX_SIZE == q->front;
}
void enqueue(Queue* q, TreeNode* node) {
if (isFull(q)) {
return;
}
q->data[q->rear] = node;
q->rear = (q->rear + 1) % MAX_SIZE;
}
TreeNode* dequeue(Queue* q) {
if (isEmpty(q)) {
return NULL;
}
TreeNode* node = q->data[q->front];
q->front = (q->front + 1) % MAX_SIZE;
return node;
}
TreeNode* buildTree(char* preorder, char* inorder, int size) {
if (size == 0) {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = *preorder;
int rootIndex = 0;
while (*(inorder + rootIndex) != *preorder) {
rootIndex++;
}
root->left = buildTree(preorder + 1, inorder, rootIndex);
root->right = buildTree(preorder + rootIndex + 1, inorder + rootIndex + 1, size - rootIndex - 1);
return root;
}
void levelOrder(TreeNode* root) {
if (root == NULL) {
return;
}
Queue q;
initQueue(&q);
enqueue(&q, root);
while (!isEmpty(&q)) {
TreeNode* node = dequeue(&q);
printf("%c ", node->val);
if (node->left != NULL) {
enqueue(&q, node->left);
}
if (node->right != NULL) {
enqueue(&q, node->right);
}
}
}
int main() {
char preorder[] = "ABDECF";
char inorder[] = "DBEAFC";
TreeNode* root = buildTree(preorder, inorder, sizeof(preorder) / sizeof(char));
levelOrder(root);
return 0;
}
```
阅读全文