Thursday, June 19, 2025
HomeC ProgrammingPlanting a Binary Tree | C For Dummies Weblog

Planting a Binary Tree | C For Dummies Weblog


Tree buildings are one more strategy to manage knowledge. They’re just like a linked record, however with the information organized by worth right into a sequence of branches and leaves. OMG! It’s like a tree!

I’m not going to get into all of the tree construction nomenclature because it’s complicated and infrequently conflicting. For this sequence, I’m specializing in a particular sort of tree, the Binary Search Tree or BST.

The BST is binary as a result of every node has two youngster nodes. Different timber can have a number of youngster nodes, however for a BST the 2 nodes characterize values: The left youngster node’s worth is lower than the basis’s worth, and the precise youngster node’s worth is larger. This group cascades down, as illustrated in Determine 1.

Determine 1. A Binary Search Tree.

In Determine 1, the basis worth holds 50. It’s youngster values are 20 (lower than, on the left) and 85 (higher than, on the precise). This sample continues, with values offered correctly left and proper.

The benefit of this construction is that it helps to shortly find knowledge. Discovering a particular worth entails traversing the tree in fewer steps than when the information is unorganized or offered sequentially.

To code a binary search tree, you want two main items: a construction and a operate.

Right here is an easy construction:

struct node {
    int key;
    struct node *left;
    struct node *proper;
};

The node wants a worth, equipped by integer variable key. Two youngster node members are left and proper, each pointers. These pointers are set to NULL until additionally they maintain values.

The second factor wanted is a operate so as to add a brand new node. It’s not simply any operate, however a recursive operate, which is designed to climb (or descend?) the tree searching for the right node into which a worth is plugged. Right here is the operate I’ve concocted:



struct node *add_node(struct node *r,int ok)
{

    if( r==NULL )
    
    {
        r = malloc( sizeof(struct node) );
        if( r==NULL )
        {
            fprintf(stderr,"Unable to allocate memoryn");
            exit(1);
        }
        r->key = ok;        
        r->proper = NULL;
        r->left = NULL;
    }
    else
    {
        
        if( ok < r->key )
            r->left = add_node(r->left,ok);
        
        else
            r->proper = add_node(r->proper,ok);
    }
    return(r);
}

The add_node() operate requires a node construction pointer and integer worth as its arguments. The operate returns a node construction pointer.

The if-else resolution within the construction handles two prospects.

The preliminary if resolution determines whether or not the deal with handed is initialized. If not (when it’s NULL), a brand new node is allotted. The worth is assigned (variable ok), and its two youngster nodes are initialized to NULL. Job executed.

The else situation handles current nodes. When the important thing worth handed (argument ok) is smaller than the present node’s key worth, a brand new node is added on the left. In any other case, the brand new node is added on the precise. These additions are made recursively, so the operate traverses the binary tree till it finds the right spot for the important thing knowledge.

The primary() operate comprises a pattern knowledge set (showing in Determine 1). It makes use of a for loop to construct the tree, outputting the values as they’re added:


int primary()
{
    static int rely = 9;
    int knowledge[] = {
        50, 20, 85, 16, 41, 59, 96, 3, 68
    };
    struct node *root = NULL;
    int x;

    
    for( x=0; x<rely; x++ )
    {
        root = add_node(root,knowledge[x]);
        printf("Added %dn",knowledge[x]);
    }

    return 0;
}

Right here’s a pattern run:

Added 50
Added 20
Added 85
Added 16
Added 41
Added 59
Added 96
Added 3
Added 68

You may view the complete code on GitHub right here.

This code is only a begin. Clearly, you have to do extra with the information than simply retailer it. The code might additionally use enchancment, in that duplicate values are added when they need to be skipped (at the very least on this instance).

One other massive subject, particularly with college college students, is that none of those nodes are freed earlier than this system ends. This course of might be dealt with by traversing the tree, a subject I cowl in subsequent week’s Lesson.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments