In: Computer Science
How to read and print all contents in a binary file using a Binary Search Tree inorder traversal in C. Additionally, how to search using a Binary Search Tree to display the specific Athlete and his/her information.
An example would be a sports record binary file that consist of name of athlete, height , weight, championships won.
Athlete: Michael Jordan
Height: 6’6”
Weight : 205 lbs
Championships won: 6
===================
Athlete: LeBron James
Height: 6’8”
Weight: 250 lbs
Championships won: 4
To traverse a binary search tree in C with the following node structure Tnode and Athelete structure
C Code
#include<stdio.h>
#include<string.h>
struct Athlete
{
char name[30];
float weight;
int ft,inch,won;
};
struct Tnode
{
struct Tnode *left;
struct Tnode *right;
struct Athlete data;
};
//inorder traversal of a BST
void inOrder(struct Tnode * root)
{
//base case when root is NULL
if(root==NULL)
return;
//GO LEFT
inOrder(root->left);
//print the athlete information
printf("Athlete: %s\n",root->data.name);
printf("Height: %d''
%d''''\n",root->data.ft,root->data.inch);
printf("Weight: %.2f
lbs\n",root->data.weight);
printf("Championships won: %d
\n",root->data.won);
//go right
inOrder(root->right);
}
//search an element in BST using athlete name
void search(struct Tnode * root,char name[30])
{
//base case when root is NULL
if(root==NULL)
return;
//GO LEFT
inOrder(root->left);
//print the athlete information if name matches
if(strcmp(name,root->data.name)==0)
{
printf("Athlete: %s\n",root->data.name);
printf("Height: %d''
%d''''\n",root->data.ft,root->data.inch);
printf("Weight: %.2f
lbs\n",root->data.weight);
printf("Championships won: %d
\n",root->data.won);
}
//go right
inOrder(root->right);
}