Even if you understand the data structure, efficient to write a tree structure, it is not easy to estimate, but since the use of STL, this is as simple as building blocks, and has a high stability.
I use the vector container as a base to form a tree.
For example, we want to generate the following structure of the tree.
3
2 2 2 2
1111 1111 1111 1111
This is a class quadtree and the lower level is 1 smaller than the upper level.
See Code://Use STL to make a tree
#include <vector>//vector containers
#include <iostream>//input/output
using namespace Std;
const int Leaves_max = 4; Maximum number of cotyledons
Tree node structure
struct TreeNode
{
int num;
Vector<treenode> Sub;
};
Vector<treenode>::iterator p; Root node pointer
Using recursive method to generate a tree
void Createtree (Vector<treenode>::iterator Root)
{
If the node value is less than or equal to 1, returns
if (root->num<=1) return;
New node pointer
TreeNode *newnode;
Set a value for a new child leaf
for (int i=1;i<=leaves_max;i++)
{
NewNode =new (TreeNode);
Newnode->num = root->num-1;
Root->sub.push_back (*newnode);
Delete NewNode;
}
Recursive generation of subtrees
Vector<treenode>::iterator child;
For (Child=root->sub.begin ();
Child!=root->sub.end ();
child++)
{
Createtree (child);
}
}
Recursively display the contents of a tree
void DisplayTree (Vector<treenode>::iterator Root)
{
Show node Contents
cout<< "" <<Root->num;
If this node has no child leaves, return
if (Root->sub.empty () ==true) return;
Recursive processing subtree
Vector<treenode>::iterator child;
For (Child=root->sub.begin ();
Child!=root->sub.end ();
child++)
{
DisplayTree (child);
}
}
void Main ()
{
TreeNode *root;
Root = new (TreeNode);
Root->num = 3;
Createtree (Root);
DisplayTree (Root);
Delete Root;
}
The results of the program execution are:
3 2 1 1 1 1 2 1 1 1 1 2 1 1 1 1 2 1 1 1 1Press any key to continue
The proof number structure has been generated successfully.
Is it very dapper with STL?
[Ref] http://www.azure.com.cn/article.asp?id=119