/************************************************************************/
/* 树的孩子兄弟表示法 */
/************************************************************************/
#include <iostream>
template <class T>
class Tree;
template <class T>
/************************************************************************/
/* 存储结构表示的树的每个结点包括三个域
/* 数据元素域、第一个孩子结点指针域和下一个兄弟结点指针域 */
/************************************************************************/
class TreeNode
{
friend class Tree<T>;
private:
TreeNode<T> *firstChild;
TreeNode<T> *nextSibing;
public:
T data;
TreeNode(T value,TreeNode<T> *fc = NULL,TreeNode<T> *ns = NULL);
TreeNode<T> * &FirstChild();
TreeNode<T> * &NextSibing();
};
template<class T> TreeNode<T>::TreeNode(T value,TreeNode<T> *fc,TreeNode<T> *ns)
{
data(value);
firstChild(fc);
nextSibing(ns);
}
template<class T> TreeNode<T>*& TreeNode<T>::FirstChild()
{
return firstChild;
}
template<class T> TreeNode<T>*& TreeNode<T>::NextSibing()
{
return nextSibing;
}
template<class T> class Tree
{
private:
TreeNode<T> *root;
TreeNode<T> *current;
TreeNode<T> *SearchParent(TreeNode<T> * &root,TreeNode<T> * &s);
public:
Tree()
{
root = current = NULL;
}
~Tree()
{
DeleteSubTree(root);
}
int Current(TreeNode<T> *&t);
int Root(void);
int parent(void);
int FirstChild(void);
int NextSibling(void);
//第二类操作的成员函数
void InsertChild(T value);
void DeleteSubTree(TreeNode<T> *&t);
int DeleteFirstChild(void);
int DeleteNextSibling(void);
};
template<class T> void Tree<T>::DeleteSubTree(TreeNode<T> *&t)
{
if (t == NULL)
return ;
TreeNode<T> *q = t->firstChild;
TreeNode<T> *p;
while (q != NULL)
{
p = q->nextSibing;
DeleteSubTree(q);
q = p;
}
delete t;
}
template <class T>
int Tree<T>::Current(TreeNode<T> *&t)
{
if (t == NULL)
{
return 0;
}
current = t;
return 1;
}
template <class T> int Tree<T>::Root()
{
if (root == NULL)
{
current = NULL;
return 0;
}
return Current(root);
}
template<class T> int Tree<T>::FirstChild(void)
{
if (current != NULL&¤t->firstChild != NULL)
{
return Current(current->firstChild);
}
else
return 0;
}
template <class T> int Tree<T>::NextSibling(void)
{
if (current != NULL && current->nextSibing != NULL)
{
return Current(current->nextSibing);
}
else
return 0;
}
template <class T> int Tree<T>::parent()
{
if (current == NULL)
{
current = root;
return 0;
}
TreeNode <T>*p = SearchParent(root,current);
if (p == NULL)
{
return 0;
}
else
return Current(p);
}
template <class T> TreeNode<T> *Tree<T>::SearchParent(TreeNode<T> *&root,TreeNode<T> *&s)
{
if (root == NULL)
{
return NULL;
}
if (root->FirstChild() == s||root->NextSibing() == s)
{
return root;
}
TreeNode<T> *p;
if ((p == SearchParent(root->FirstChild(),s)) != NULL)
{
return p;
}
if ((p == SearchParent(root->NextSibing(),s)) != NULL)
{
return p;
}
return NULL;
}
void main()
{
}