We use them all the time. In C++, no one implements linked lists anymore, we just use std::list.
There isn't a standard tree class as such, but some containers are implemented using trees such as map, multimap, set, ... almost all of those containers that have a sorted key use a tree implementation internally.
Just to work thru a tree example, I'll do it without using classes first.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
|
#include <string>
#include <iostream>
struct Node
{
typedef std::string value_type;
const value_type value;
Node* lptr;
Node* rptr;
Node(value_type value) : value(value) { lptr = rptr = 0; }
};
void insert(Node **tree, Node::value_type value)
{
if (*tree == 0)
{
*tree = new Node(value);
return;
}
if (value < (*tree)->value)
insert(&((*tree)->lptr), value);
else
insert(&((*tree)->rptr), value);
}
void print(Node* tree, std::ostream &os)
{
if (tree)
{
print(tree->lptr, os);
os << tree->value << std::endl;
print(tree->rptr, os);
}
}
int main()
{
Node* planets = 0;
insert(&planets, "Mars");
insert(&planets, "Saturn");
insert(&planets, "Earth");
insert(&planets, "Jupiter");
insert(&planets, "Pluto");
Node* cities = 0;
insert(&cities, "Paris");
insert(&cities, "Orleans");
insert(&cities, "Lyon");
insert(&cities, "Bordeaux");
insert(&cities, "Monaco");
print(cities, std::cout);
print(cities, std::cout);
return 0;
}
|
We now have a tree structure that stores strings. Note the following.
1. Node just holds the value and pointers.
2. The Node constructor conveniently initialises members.
3. There's only one constructor as we only create Nodes in one way.
4. We could disable copy on Node as it should never be copied, but that's distracting in this example.
5. The tree operations are not members of Node, they take the root node as a parameter. At present the operations are global functions, but eventually we'd encapsulate them in a Tree class.
6. Tree operations are recursive.
7. You must work with Node* in your program and you must explicitly initialise it to zero yourself.
8. I've not shown deletion, but the tree should be deleted on exit.