Binary Tree in C++ – 1

We create a toolkit of functions useful for a binary tree.

A binary tree is a tree where every node has at most 2 children – the left and the right child. Each node, other than the root, has exactly one parent. The root has no parent.

We define a struct for a node of the binary tree, containing the data stored in the node, apart from the pointers to the left and the right child. One could also include, if they wish, pointers to the parent and to siblings.

——-

struct Node

{

typedef char Item;

Item data;

Node* left_ptr;

Node* right_ptr;

};

————–

We now look at a few functions to manipulate a binary tree.

1. The create_node function creates a new node using the arguments passed to it.

void create_node ( const Item& data, Node* l_ptr = 0, Node* r_ptr = 0);

———

The default values for the left and right child pointers have been set to null.

Node* create_node (const Item& data, Node* l_ptr = 0, Node* r_ptr)

{

Node* myNode_ptr;

myNode_ptr -> data = data;

myNode_ptr -> left_ptr = l_ptr;

myNode_ptr -> right_ptr = r_ptr;

return myNode_ptr;

}

——–

2. Another simple function checks if a node is a leaf – i.e. if both of its children are null.

bool is_leaf (const Node* node_ptr)

{

if (! node_ptr)

return false;

return ( ! (node_ptr -> left_ptr) &&  ! (node_ptr -> right_ptr) );

}

——–

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: