利用队列,编程实现二叉树的层次遍历。 输入格式: 一个字符序列,表示空子树处为*号的二叉树的先序遍历序列。C语言 输出格式: 一个字符序列,表示二叉树的层次遍历序列。输入样例: abd*f***ce*** 输出样例: abcdef
时间: 2023-08-03 21:03:11 浏览: 100
好的,以下是 C 代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
char val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
TreeNode* buildTree(char** preorder) {
char* val = *preorder;
(*preorder)++;
if (*val == '*' || *val == '\0') {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = *val;
root->left = buildTree(preorder);
root->right = buildTree(preorder);
return root;
}
void levelOrder(TreeNode* root) {
if (!root) {
return;
}
TreeNode** queue = (TreeNode**)malloc(sizeof(TreeNode*) * 100);
int front = 0, rear = 0;
queue[rear++] = root;
while (front < rear) {
int size = rear - front;
for (int i = 0; i < size; i++) {
TreeNode* node = queue[front++];
printf("%c", node->val);
if (node->left) {
queue[rear++] = node->left;
}
if (node->right) {
queue[rear++] = node->right;
}
}
}
}
int main() {
char preorder[100];
scanf("%s", preorder);
char* p = preorder;
TreeNode* root = buildTree(&p);
levelOrder(root);
return 0;
}
```
输入示例:
```
abd*f***ce***
```
输出示例:
```
abcdef
```
阅读全文