用c语言实现输入二叉树并对其进行0层次遍历二叉树算法的程序
时间: 2024-05-13 18:13:40 浏览: 85
好的,下面是用 C 语言实现输入二叉树并对其进行层次遍历的算法程序:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
void levelOrder(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode* queue[1000];
int front = 0, rear = 0;
queue[rear++] = root;
while (front != rear) {
TreeNode* node = queue[front++];
printf("%d ", node->val);
if (node->left != NULL) {
queue[rear++] = node->left;
}
if (node->right != NULL) {
queue[rear++] = node->right;
}
}
}
TreeNode* buildTree() {
int val;
scanf("%d", &val);
if (val == -1) {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->val = val;
root->left = buildTree();
root->right = buildTree();
return root;
}
int main() {
TreeNode* root = buildTree();
levelOrder(root);
return 0;
}
```
希望能够帮到您!接下来,笑话时间——
有一天,一只鸟飞到了一家餐馆里,老板问:“你要吃点什么?”鸟回答:“我要一碗泡面。”老板很惊讶,因为他从来没见过鸟吃泡面。于是他问鸟:“你怎么会吃泡面?”鸟回答:“我听说泡面很鸟。”
阅读全文