template <class Item>
struct BinaryTreeNode
{
Item data;
BinaryTreeNode *left;
BinaryTreeNode *right;
};
template <class Item>
BinaryTreeNode<Item>* create_node(
const Item& entry,
BinaryTreeNode<Item>* l_ptr = NULL,
BinaryTreeNode<Item>* r_ptr = NULL
)
{
BinaryTreeNode<Item> *result_ptr;
result_ptr = new BinaryTreeNode<Item>;
result_ptr->data = entry;
result_ptr->left = l_ptr;
result_ptr->right = r_ptr;
return result_ptr;
}
template <class Item>
bool is_leaf(const BinaryTreeNode<Item>& node)
{
return (node.left == NULL) && (node.right == NULL);
}
template <class Item>This function is simple to write because it is recursive. The base case is the empty tree. In that case there is nothing to do. Otherwise, we clear the left subtree, then clear the right subtree, then delete the root and set the root pointer to NULL. Clearing a subtree is a smaller version of the original problem and thus leads to a recursive solution.
void tree_clear(BinaryTreeNode<Item>*& root_ptr)
{
if (root_ptr != NULL)
{
tree_clear(root_ptr->left);
tree_clear(root_ptr->right);
delete root_ptr;
root_ptr = NULL;
}
}
template <class Item>This function is also recursive. The base case is again the empty tree. If the tree is not empty then we copy its left subtree, then copy its right subtree, then create a root node and attach the two subtrees to its left child and right child. Copying a subtree is a smaller version of the original problem and thus leads to the recursive solution.
BinaryTreeNode<Item>* tree_copy(BinaryTreeNode<Item>* root_ptr)
{
BinaryTreeNode<Item> *l_ptr;
BinaryTreeNode<Item> *r_ptr;
If (root_ptr == NULL)
return NULL;
else
{
l_ptr = tree_copy(root_ptr->left);
r_ptr = tree_copy(root_ptr->right);
return create_node(root_ptr->data, l_ptr, r_ptr);
}
}