Answer to Question #264385 in C for Karan

Question #264385

Write a program for Linked-list implementation of a complete binary tree. The program must


have the following functionalities.


a) Insert(): inserts a new ITEM to the complete binary tree. The items are of integer type.


b) Height(): returns height of a node recursively. Height (N) = MAX(Height(L), Height(R))


+ 1. Here, L and R respectively represent the Left child and Right child of node N. Height


of a leaf node is 0.


c) Preorder(): returns the preorder traversal sequence of the binary tree. Use recursive


implementation.


d) Postorder(): returns the postorder traversal sequence of the binary tree. Use recursive


implementation.

1
Expert's answer
2021-11-11T17:37:41-0500
#include <stdio.h>
#include <stdlib.h>
 


struct Binary {
    int item;
    struct Binary* left;
    struct Binary* right;
};
 


struct Binary* insert(int data)
{
    struct Binary* head= (struct Binary*)malloc(sizeof(struct Binary));
    head->item = data;
    head->left = NULL;
    head->right = NULL;
 
    return (head);
}
 int Height(struct Binary* head)
{
	int i = 0;
   
 
   
    Height(head->left);
 
    
    Height(head->right);
 
    
    i++;
    
    return i;
}
 


void Postorder(struct Binary* head)
{
    if (head == NULL)
        return;
 
   
    Postorder(head->left);
 
    
    Postorder(head->right);
 
    
    printf("%d ", head->item);
}
 




void Preorder(struct Binary* head)
{
    if (head == NULL)
        return;
 
    printf("%d ", head->item);
 
   
    Preorder(head->left);


    Preorder(head->right);
}
 
int main()
{
    struct Binary* head = insert(1);
    head->left = insert(2);
    head->right = insert(3);
    head->left->left = insert(4);
    head->left->right = insert(5);
 
    printf("\nPreorder traversal \n");
    Preorder(head);
 
    
    printf("\nPostorder traversal \n");
    Postorder(head);
 
    getchar();
    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS