A binary tree structure is defined as follows: struct Tree { int item; struct Tr
ID: 3860160 • Letter: A
Question
A binary tree structure is defined as follows: struct Tree { int item; struct Tree * left_child; struct Tree * right_child; } If a left child or right child does not exist, the corresponding member variable is set to NULL. Write a function int print_level(struct Tree * tree) that prints the nodes in LEVEL-ORDER, but for each node, IT ALSO PRINTS THE LEVEL. Your program should not crash. If it is easier, you can assume you already have implementations for lists, stacks and queues of integers that you can use in your function.
Explanation / Answer
#include <stdio.h>
#include <conio.h>
struct node
{
int data;
struct node *lchild,*rchild;
};
typedef struct node bnode;
bnode* getnode(int ele)
{
bnode *q = (bnode*)malloc(sizeof(bnode));
if(q)
{
q -> data = ele;
q -> lchild = NULL;
q -> rchild = NULL;
return q;
}
else
{
printf(" Unable to create the node");
exit(0);
}
return 0;
}
bnode* insert(bnode *root, int ele)
{
if(!root)
{
bnode *q = getnode(ele);
root = q;
}
else
if(root->data < ele)
root->rchild = insert(root->rchild, ele);
else
if(root -> data > ele)
root -> lchild = insert(root -> lchild, ele);
else
{
printf(" Duplicate data ");
}
return root;
}
void main() {
int ch, ele;
bnode *root = NULL;
printf(" Binary Search Tree Operations :");
printf(" 1) Insert 2) Exit");
while(1) {
printf(" Enter your choice :");
scanf("%d", &ch);
switch(ch) {
case 1: printf(" Enter an element :");
scanf("%d", &ele);
root = insert(root, ele); break;
case 2: exit(0);
default : printf(" Invalid choice.");
}//switch
}
}//main
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.