75 lines
1.6 KiB
C
75 lines
1.6 KiB
C
#include <stdint.h>
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
typedef struct tree {
|
|
int key;//datatype
|
|
struct tree *left, *right;
|
|
struct tree *parent; // необязательное поле
|
|
} tree;
|
|
|
|
//Вычисляем высоту дерева
|
|
int heightTree(tree* p)
|
|
{
|
|
if (p == NULL)
|
|
return 0;
|
|
else
|
|
{
|
|
/* вычисляем высоту каждого поддерева */
|
|
int lheight = heightTree(p->left);
|
|
int rheight = heightTree(p->right);
|
|
|
|
if (lheight > rheight)
|
|
return (lheight + 1);
|
|
else
|
|
return (rheight + 1);
|
|
}
|
|
}
|
|
//Печатаем все узлы на уровне level
|
|
void printCurrentLevel(tree* root, int level)
|
|
{
|
|
if (root == NULL)
|
|
return;
|
|
if (level == 1)
|
|
printf("%d ", root->key);
|
|
else if (level > 1)
|
|
{
|
|
//если поменять местами то будет обход справа на лево
|
|
printCurrentLevel(root->right, level - 1);
|
|
|
|
printCurrentLevel(root->left, level - 1);
|
|
}
|
|
}
|
|
//функция печати
|
|
void printBFS(tree* root)
|
|
{
|
|
int h = heightTree(root);
|
|
for (int i = 1; i <= h; i++)
|
|
printCurrentLevel(root, i);
|
|
}
|
|
|
|
int main(void)
|
|
{
|
|
tree *tr = NULL;
|
|
|
|
tr = calloc(1,sizeof(tree));
|
|
tr->key = 1;
|
|
|
|
tr->right = calloc(1,sizeof(tree));
|
|
tr->right->key = 5;
|
|
|
|
tr->left = calloc(1,sizeof(tree));
|
|
tr->left->key = 2;
|
|
|
|
tr->left->left = calloc(1,sizeof(tree));
|
|
tr->left->left->key=3;
|
|
|
|
tr->left->right = calloc(1,sizeof(tree));
|
|
tr->left->right->key=4;
|
|
|
|
printf("BFS (Breadth First Traversal)\n");
|
|
printBFS(tr);
|
|
|
|
return 0;
|
|
}
|