Binary Tree in C++ – 1
February 15, 2011 Leave a comment
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.
typedef char Item;
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)
myNode_ptr -> data = data;
myNode_ptr -> left_ptr = l_ptr;
myNode_ptr -> right_ptr = r_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 ( ! (node_ptr -> left_ptr) && ! (node_ptr -> right_ptr) );