【发布时间】:2013-02-28 03:37:20
【问题描述】:
我目前正在尝试使用具有未知数量的子节点的树结构,但我还必须跟踪父节点。我查看了这个问题N-ary trees in C 并制作了类似于链接中建议的结构:
template <class T>
struct treeNode {
public:
T * data;
treeNode *parent;
treeNode *kids; //left
treeNode *siblings; //right
treeNode();
~treeNode();
treeNode(T data);
void treeInsert(T newItem);
};
它说通过以这种方式制作树,可以使某些算法更容易编码。但是,我很难弄清楚如何为此结构创建 insert() 和 search() 方法,因为我需要跟踪父节点。有什么建议可以解决这个问题吗?
编辑:
这是我的 insert() 方法:
template<class T>
bool NewTree<T>::insert( T *data, treeNode<T> * parent)
{
if(this->root == NULL)
{
this->root = new treeNode<T>();
this->root->data = data;
this->root->parent = NULL;
this->root->children = NULL;
}
else
{
treeNode temp = new treenode<T>();
temp.data = data;
temp.parent = parent;
parent->children->siblings = temp; // add node to siblings of parent's children
parent->children = temp; // add node to children of parent
}
}
这看起来正确吗?
【问题讨论】:
标签: c++ tree binary-tree