Lesson 1 of 14

The Node

Binary Trees

A binary tree is a data structure where each node has at most two children — a left child and a right child. Trees model hierarchical data: file systems, HTML documents, organization charts, and more.

        4
       / \
      2   6
     / \ / \
    1  3 5  7

The Node Struct

Every node holds a value and two child pointers:

struct Node {
    int val;
    struct Node *left;
    struct Node *right;
};

Creating Nodes

Allocate each node with malloc. Set left and right to NULL — a NULL pointer means no child:

struct Node *new_node(int val) {
    struct Node *n = (struct Node *)malloc(sizeof(struct Node));
    n->val = val;
    n->left = NULL;
    n->right = NULL;
    return n;
}

Building a Tree

Link nodes together by assigning children:

struct Node *root = new_node(4);
root->left = new_node(2);
root->right = new_node(6);
root->left->left = new_node(1);

Your Task

Implement struct Node *new_node(int val) that allocates a node with the given value and NULL children. Create a root node with value 10 and print its value.

TCC compiler loading...
Loading...
Click "Run" to execute your code.