C program to find the largest item in the binary tree

Here, we are going to learn how to find the largest item in the binary tree using C program?
Submitted by Nidhi, on August 24, 2021

Problem Solution:

Create a binary tree, and then find the largest item from the binary tree.

Program:

The source code to find the largest item in the binary tree is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to find the largest item
// in binary tree

#include <stdio.h>
#include <stdlib.h>

typedef struct node {
    int item;
    struct node* left;
    struct node* right;

} Node;

void AddNode(Node** root, int item)
{
    Node* temp = *root;
    Node* prev = *root;

    if (*root == NULL) {
        *root = (Node*)malloc(sizeof(Node));

        (*root)->item = item;
        (*root)->left = (*root)->right = NULL;
    }
    else {
        while (temp != NULL) {
            if (item > temp->item) {
                prev = temp;
                temp = temp->right;
            }
            else {
                prev = temp;
                temp = temp->left;
            }
        }
        temp = (Node*)malloc(sizeof(Node));
        temp->item = item;

        if (item >= prev->item)
            prev->right = temp;
        else
            prev->left = temp;
    }
}

void FindLarge(Node* root, int* large)
{
    if (root != NULL) {
        FindLarge(root->left, large);

        if (*large < root->item)
            *large = root->item;

        printf("%d ", root->item);
        FindLarge(root->right, large);
    }
}

int main()
{
    Node* root = NULL;

    int large = 0;

    AddNode(&root, 10);
    AddNode(&root, 20);
    AddNode(&root, 60);
    AddNode(&root, 50);
    AddNode(&root, 40);

    printf("Inorder traversing:\n");
    FindLarge(root, &large);

    printf("\nLargest item is: %d\n", large);

    return 0;
}

Output:

Inorder traversing:
10 20 40 50 60 
Largest item is: 60

Explanation:

Here, we created a self-referential structure to implement a Binary Tree, a function to add a node into the binary tree, and a recursive function FindLarge() to find the largest item from the binary tree.

In the main() function, we created a binary search tree and called the function FindLarge() to find the largest item from the binary tree.

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




© https://www.includehelp.com some rights reserved.