C program to implement depth-first binary tree search using recursion

Here, we are going to learn how to implement depth-first binary tree search using recursion in C language?
Submitted by Nidhi, on August 24, 2021

Problem Solution:

Create a binary tree and implement a depth-first binary search and print the nodes.

Program:

The source code to depth-first binary tree search using recursion is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to implement depth-first binary tree search
// using recursion

#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 DFS(Node* root)
{
    if (root) {
        if (root->left)
            DFS(root->left);

        if (root->right)
            DFS(root->right);

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

int main()
{
    struct node* head = NULL;
    AddNode(&head, 10);
    AddNode(&head, 20);
    AddNode(&head, 40);
    AddNode(&head, 30);
    AddNode(&head, 60);

    DFS(head);
    printf("\n");

    return 0;
}

Output:

30  60  40  20  10

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 DFS() to implement depth-first search and print the nodes.

In the main() function, we created a binary search tree, and called the function DFS() to print the nodes.

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Top MCQs

Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

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