【问题标题】:how to get an element in n-ary trees如何在n叉树中获取元素
【发布时间】:2014-01-11 05:01:59
【问题描述】:

我遇到了一个关于 n 叉树的问题。我想得到一个元素的指针,给定根指针和元素的名称。我尝试以递归方式编写它,但出现分段错误。

Node* findNode(Node* ptr, const string& name)
{   
    if(ptr->getNextSibling() == NULL)
        return NULL;
    if(ptr->getFirstChild() == NULL)
       return NULL;

    if(ptr->getName() == name)

            return ptr;     
    else
    {
        findNode(ptr->getNextSibling(), name);
        findNode(ptr->getFirstChild(), name);   
    }   

}

n 叉树由指向其下一个子节点的指针、指向其下一个兄弟节点的指针、指向根节点的指针和数据组成。

【问题讨论】:

  • 您正在测试if(ptr->getNextSibling() == NULL) 两次。也许您打算测试getFirstChild()
  • 嗯,这是真的。但它仍然没有改变任何东西
  • 它仍然不能使函数正常工作,但它应该停止段错误。

标签: c++ recursion tree


【解决方案1】:

基本的二分搜索看起来有点像这样:

Node* findNode(Node* ptr, const string& name)
{   
    if(ptr == NULL)
        return NULL;

    if(ptr->getName() == name)
        return ptr;     

    Node *pTarget = findNode(ptr->getLeftChild(), name);
    if (pTarget == NULL)
        pTarget = findNode(ptr->getRightChild(), name);   

    return pTarget;  // might be NULL
}

n 元搜索可能看起来更像这样:

Node* findNode(Node* ptr, const string& name)
{   
    if(ptr == NULL)
        return NULL;

    if(ptr->getName() == name)
            return ptr;   

    for (Node *pChild=ptr->getFirstChild(); 
         pChild!=NULL; 
         pChild=pChild->getNextSibling())
    {
        Node *pTarget = findNode(pChild, name);
        if (pTarget != NULL)
            return pTarget;
    }

    return NULL;  
}

我还没有编译或测试过这个,但我认为算法还可以(尽管不是最理想的)。

【讨论】:

  • 实际上我正在尝试更改它,但 MS 病毒扫描程序启动并挂起我的机器。我刚刚重新启动。我展示的算法不会调用 getFirstChild() 和 getNextSibling(),它会调用 getLeftChild() 和 getRightChild()。 getFirst/getNext 表明每个节点可能有多个(超过 2 个)子节点。
【解决方案2】:

在n叉树中找一个元素会是这样的。

Tr* search(Tr *root, const string& name) //search Element with ID
{
    Tr *element;
    if (!root) return NULL;
    if (root->getname()== name)return root; 
    while (root != NULL)
    {

        if ((element = search(root->child, id)) != NULL)
        {
            return element;
        }
        root = root->sibling; 
    } 
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-07
    • 2011-02-06
    • 2015-05-21
    相关资源
    最近更新 更多