Answer to Question #290427 in C for Srop

Question #290427

For the given data construct Binary Search tree and obtain pre-order , post order and In-


order transversal ( Data set: -90,0,78,20,34,678,32,56,56).

1
Expert's answer
2022-01-25T07:51:17-0500
#include <stdio.h>
#include <stdlib.h>


typedef struct Node_ {
    int data;
    struct Node_* left;
    struct Node_* right;
} Node;


Node* add_node(Node* tree, int value) {
    if (!tree) {
        Node* new_node = (Node*) malloc(sizeof(Node));
        new_node->left = new_node->right = NULL;
        new_node->data = value;
        return new_node;
    }
    if (value < tree->data) {
        tree->left = add_node(tree->left, value);
    }
    else {
        tree->right = add_node(tree->right, value);
    }
    return tree;
}


void free_tree(Node* tree) {
    if (tree->left) {
        free_tree(tree->left);
    }
    if (tree->right) {
        free_tree(tree->right);
    }
    free(tree);
}


void print_preorder(Node* tree) {
    printf("%d ", tree->data);
    if (tree->left) {
        print_preorder(tree->left);
    }
    if (tree->right) {
        print_preorder(tree->right);
    }
}


void print_postorder(Node* tree) {
    if (tree->left) {
        print_postorder(tree->left);
    }
    if (tree->right) {
        print_postorder(tree->right);
    }
    printf("%d ", tree->data);
}


void print_inorder(Node* tree) {
    if (tree->left) {
        print_inorder(tree->left);
    }
    printf("%d ", tree->data);
    if (tree->right) {
        print_inorder(tree->right);
    }
}


int main() {
    Node* tree=NULL;
    int data[] = {-90,0,78,20,34,678,32,56,56};
    int n =  sizeof(data) /sizeof(data[0]);
    int i;


    for (i=0; i<n; i++) {
        tree = add_node(tree, data[i]);
    }


    printf("Preorder:\n");
    print_preorder(tree);


    printf("\n\nPostorder:\n");
    print_postorder(tree);


    printf("\n\nInorder:\n");
    print_inorder(tree);


    free_tree(tree);
    return 0;
}


Preorder:
-90 0 78 20 34 32 56 56 678

Postorder:
32 56 56 34 20 678 78 0 -90

Inorder:
-90 0 20 32 34 56 56 78 678

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