N元树的二元表示

时间:2013-02-28 03:37:21

标签: c++ tree binary-tree

我目前正在尝试使用具有未知数量的子节点的节点来构建树结构,但我还必须跟踪父节点。我查看了这个问题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

}

}

这看起来是否正确?

1 个答案:

答案 0 :(得分:0)

对于任何树结构,搜索将使用相对相同的算法(如果未排序则为深度优先递归,或者如果排序则为简单树搜索(如二叉搜索树))。插入时,您需要做的就是将新节点的.parent分配给父节点。然后将新节点的.parent.child[1]分配给新节点(从而将父节点链接到子节点)。然后,检查父节点的其他子节点以分配新节点的兄弟节点(如果有)。

好的,所以这里有一些伪代码(大多数像java - 抱歉,这就是我今天所写的内容),它将实现节点创建和一系列赋值,以便在树结构中维护它,使用第二个例子。您提供的链接:

(节点来源):

class Node {
  // generic data store
  public int data;
  public Node parent;
  public Node siblings;
  public Node children;
}

(树源):

class NewTree {
  // current node
  public Node current;
  // pointer to root node
  public Node root;

  // constructor here
  // create new node
  public boolean insert(int data) {
    // search for the node which is immediately BEFORE where the new node should go
    // remember that with duplicate data values, we can just put the new node in
    // front of the chain of siblings
    Node neighbor = this.search(data);
    // if we've found the node our new node should follow, create it with the 
    // found node as parent, otherwise we are creating the root node
    // so if we're creating the root node, we simply create it and then set its
    // children, siblings, and parent to null
    // i think this is the part you're having trouble with, so look below for a 
    // diagram for visual aid
  }

  public Node search(int target) {
    // basically we just iterate through the chain of siblings and/or children 
    // until this.current.children is null or this.current.siblings is null
    // we need to make certain that we also search the children of 
    // this.index.sibling that may exist (depth-first recursive search)
  }
}

当我们找到新节点所在的地点(使用search())时,我们需要将新节点内的父节点,子节点和兄弟节点“链接”重新分配给新的父节点,子节点和兄弟节点。例如,我们采取这个:

A-|
|
B-C-|
| |
| F-G-|  
| |
| -
|
D-E-|
| |
- H-|
  |
  -

我们将插入一个新节点(X),其中F为。这只是为了说明我们如何重新分配每个新节点的链接。更精细的细节可能略有不同,但重要的是链接重新分配的实现示例:

A-|
|
B-C-|
| |
| X-F-G-|  
| | |
| - -
|
D-E-|
| |
- H-|
  |
  -

我们所做的是:1)创建X. 2)将x.parent分配给c。 3)将c.children重新分配给x。 4)将x.siblings分配给f。这会插入一个新节点(请注意插入与排序不同,如果明确要求特定排序,则树可能需要求助)。

相关问题