Course contentsShow
← C
Lesson 1022 of 1,21914. Data Structures in CFree lesson

Recursive tree node structure

Recursive tree node structure

What you'll learn: How to define a self-referential structure that allows a single C struct to point to two other versions of itself, forming the foundation of a binary tree.

The "Family Tree" Blueprint

Imagine you are designing a digital filing cabinet. In a simple list, one folder just sits behind another. But in a Binary Search Tree (BST), each folder is a "node" that has two arms. To represent this in C, we need a structure that is recursive.

A recursive structure is a bit of a magic trick: it is a struct that contains pointers to other instances of the exact same struct type. In a BST, every node acts as a miniature root for two smaller trees beneath it.

Defining the Node

To build this, we use struct. Inside, we need three things:

  1. The data (like an integer).
  2. A pointer to a left child.
  3. A pointer to a right child.

Here is how that looks in code:

#include <stdio.h>

struct Node {
    int data;                // The value stored in this node
    struct Node* left;       // Pointer to the left child node
    struct Node* right;      // Pointer to the right child node
};

Notice the struct Node* syntax inside the definition. We can't put a whole struct Node inside itself (that would be like trying to put a box inside an identical-sized box), but we can store the memory address (a pointer) of another node.

Why Two Pointers?

Think of each node as a fork in the road. When you are standing at a node, the left pointer leads you to a whole new subtree where all the values are smaller, and the right pointer leads to a subtree where all the values are larger.

If a node doesn't have a child (it’s at the very end of a branch), we simply set that pointer to NULL. This tells our program, "The road ends here." By linking these nodes together via these recursive pointers, we create a branching web that can hold millions of items while remaining incredibly fast to search.

Key takeaway

A BST node is a self-referential structure that uses two pointers of its own type to branch out into left and right subtrees.