Why do we use left and right node pointers within the node structure?

Viewed 560

This is the class binary search tree

Why do we create nodes left and right pointer within the node structure which will again have 3 attributes? Why not just use an int?

class bst
{
 struct node
    {
        int key;
        node *left;
        node *right;
    };
    node *root;
};
1 Answers

Following your comment, I believe I understand your confusion.

The reason the node structure contains pointers to other node structures and not to int is to allow the tree to have multiple levels.

Each node has a value, and can have one or two children nodes, but each of those nodes can have its own children.

BST - a binary search tree, can grow as large as your computer memory will allow, depending on how much data you want to store in it.

Look at this image (taken from Wikipedia):

Binary Search Tree

If you used pointers to int you could only store 8, 3, and 10, but would have no way to store 1, 6, 14 and the rest of the values.

But with every node containing a value and a pointer to other nodes you can chain as many of them as you need.

Related