c语言按层次遍历二叉树代码
时间: 2023-06-06 19:07:24 浏览: 67
层次遍历二叉树C语言实现
4星 · 用户满意度95%
以下是 C 语言按层次遍历二叉树的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* left;
struct node* right;
};
struct node* create_node(int data) {
struct node* new_node = (struct node*)malloc(sizeof(struct node));
new_node->data = data;
new_node->left = NULL;
new_node->right = NULL;
return new_node;
}
int height(struct node* node) {
if (node == NULL)
return 0;
else {
int left_height = height(node->left);
int right_height = height(node->right);
if (left_height > right_height)
return (left_height + 1);
else
return (right_height + 1);
}
}
void print_given_level(struct node* root, int level) {
if (root == NULL)
return;
if (level == 1)
printf("%d ", root->data);
else if (level > 1) {
print_given_level(root->left, level - 1);
print_given_level(root->right, level - 1);
}
}
void print_level_order(struct node* root) {
int h = height(root);
int i;
for (i = 1; i <= h; i++)
print_given_level(root, i);
}
int main() {
struct node* root = create_node(1);
root->left = create_node(2);
root->right = create_node(3);
root->left->left = create_node(4);
root->left->right = create_node(5);
root->right->left = create_node(6);
root->right->right = create_node(7);
printf("Level order traversal of binary tree is: ");
print_level_order(root);
return 0;
}
```
阅读全文