template <class T>
class Tree
{
Tree()
:_root(NULL)
{}
void Clear();
Tree_Node<T>* Find(T value);
bool Add_Node(T parent, T child);
int size();
int Height();
int Leaves();
bool empty();
private:
Tree_Node<T> *Find_R(Tree_Node<T>*root, T value);
int Tree::Height_R(Tree_Node<T>* root);
int Tree::Size_R(Tree_Node<T>* root);
int Tree::Leaves_R(Tree_Node<T>* root);
private:
Tree_Node<T>* _root;
};
3、樹(shù)的基本操作
3.1、 插入
template <class T>
bool Tree::Add_Node(T parent, T child)
{
if( _root == NULL )
{ /*設(shè)置為根節(jié)點(diǎn)*/
_root = new Tree_Node(child, NULL);
return true;
}
/*尋找值 = parent的節(jié)點(diǎn)*/
Tree_Node* cur = Find(parent);
Tree_Node* child = new Tree_Node(child, NULL);
cur->_children.push_back(child);
}
3.2、查詢
template <class T>
Tree_Node<T>* Tree::Find( T value )
{
return Find_R(_root, value);
}
template <class T>
Tree_Node<T>* Tree::Find_R(Tree_Node<T>* root, T value)
{
if ( root->value == value )
return root;
for(auto &child: root->children)
{
Find_R(child, value);
}
return NULL;
}