使用队列

时间:2015-08-09 22:12:33

标签: c++ data-structures tree

我有一个简单的n-ary(最多3个子节点),其中插入的第一个节点将是根。以前,我添加任何其他节点,我必须搜索树并插入作为子节点从先前插入的节点,如果条件满足。 我的插入方法因首次插入和后续插入而过载。

我能够使用此方法插入第一个节点:

void Tree::AddSkill(char* name, char* desc, int level)
{
    Skill s(name, desc, level);
    Node * newNode = new Node(s);
    //newNode->aSkill = Skill(name, desc, level);

    newNode->parent = NULL;
    for (int i = 0; i<CHILD_MAX; i++)
    {
        newNode->children[i] = NULL;
    }

    if (this->root == NULL)
    {
        this->root = newNode;
    }
    else
    {
        this->root->parent = newNode;
        newNode->children[0] = this->root;
        this->root = newNode;
    }
}

我在后续插入树时遇到一些问题, 这是我到目前为止的代码:

void Tree::AddSkill(char* name, char* desc, int level, char* parentName)
{
    if (this->root == NULL)
    {
        cout << "Error: no nodes in tree.\n";
        return;
    }

    Node* node = NULL;
    Skill s(name, desc, level);
    Node * child = new Node(s);
    while (root != NULL)
    {
        if (strcmp(child->aSkill.GetName(), parentName) == 0)
        {
            for (int i = 0; i < CHILD_MAX; i++)
            {
                if (node->children[i] == NULL)
                {
                    child->aSkill = s;
                    child->parent = node;
                    node->children[i] = child;
                    return;
                }
            }
        }
    }
}

当我通过VS Debugger运行代码时,第二个AddSkill方法中的while循环会无休止地重复。 我不太确定我做错了什么或我需要实施什么概念,我们将不胜感激。

P.S。这是一个家庭作业(不确定适当的标签是什么)。

更新: 我尝试使用Queue实现重载AddSkill()。 这就是我尝试过的。

void SkillTree::AddSkill(char* name, char* desc, int level, char* parentName)
{
    if (this->root == NULL)
    {
        cout << "Error: no nodes in tree.\n";
        return;
    }  
    queue<Node*> q;
    q.push(this->root);
    while (!q.empty())
    {
        Node * n = q.front();
        q.pop();    
        if (strcmp(n->aSkill.GetName(), parentName) == 0)
        {
            for (int i = 0; i<CHILD_MAX; i++)
            {
                if (n->children[i] == NULL)
                {
                    Skill s(name, desc, level);
                    Node * child = new Node(s);
                    //When I comment out the next 3 lines, program does not crash. Not sure what the problem is here.
                    child->aSkill = s;
                    child->parent = n;
                    n->children[i] = child;
                    return;
                }
            }
            return;
        }
        for (int i = 0; i<CHILD_MAX; i++)
        {
            if (n->children[i] != NULL)
            {
                q.push(n->children[i]);
            }
        }
    }
}

技能等级

#include <iostream>
#include "Skill.h"
Skill::Skill()
{
    name = NULL;
    desc = NULL;
    level = 0;
}

Skill::Skill(char* name, char* desc, int level) : level(level), name(new char[strlen(name) + 1]), desc(new char[strlen(desc) + 1])
{
    strcpy_s(this->name, (strlen(name) + 1), name);
    strcpy_s(this->desc, (strlen(desc) + 1), desc);
}

Skill::Skill(const Skill& aSkill)
{
    this->name = new char[strlen(aSkill.name) + 1];
    strcpy_s(this->name, (strlen(aSkill.name) + 1), aSkill.name);

    this->level = aSkill.level;

    this->desc = new char[strlen(aSkill.desc) + 1];
    strcpy_s(this->desc, (strlen(aSkill.desc) + 1), aSkill.desc);
}

Skill& Skill::operator=(const Skill& aSkill)
{
    if (this == &aSkill)
        return *this;
    else
    {
        delete[] name;
        delete[] desc;

        name = new char[strlen(aSkill.name) + 1];
        strcpy_s(name, (strlen(aSkill.name) + 1), aSkill.name);

        desc = new char[strlen(aSkill.desc) + 1];
        strcpy_s(name, (strlen(aSkill.desc) + 1), aSkill.desc);

        level = aSkill.level;

        return *this;
    }
}

Skill::~Skill()
{
    delete[] name;
    delete[] desc;
}

char* Skill::GetName() const
{
    return name;
}
char* Skill::GetDesc() const
{
    return desc;
}
int Skill::GetLevel() const
{
    return level;
}

void Skill::Display(ostream& out)
{
    out << "- " << GetName() << " -- " << GetDesc() << " [Lvl: " << GetLevel() << "]\n";
}

节点:

    Skill aSkill;
    Node* parent;
    Node* children[CHILD_MAX];
    Node() : parent(NULL)
    {
        for (int i = 0; i < CHILD_MAX; i++)
        {
            children[i] = NULL;
        }
    };

    Node(const Skill& n) : aSkill(n), parent(NULL)
    {
        for (int i = 0; i < CHILD_MAX; i++)
        {
            children[i] = NULL;
        }
    };

以下是main()

的摘录
SkillTree student("Student");
    student.Display(cout);

    student.AddSkill("Alphabet","Mastery of letters and sounds",0);
    student.Display(cout);

    student.AddSkill("Reading","The ability to read all manner of written material",1,"Alphabet");
    student.AddSkill("Writing","The ability to put your thoughts on paper",1,"Alphabet");
    student.Display(cout); 
student.AddSkill("Speed Reading Level 1","Read any text twice as fast as normal",5,"Reading");
student.AddSkill("Speed Reading Level 2","Read any text four times as fast as normal",10,"Speed Reading Level 1");
student.AddSkill("Memorization","Memorize average sized texts",10,"Reading");
student.AddSkill("Massive Memorization","Memorize large sized texts",20,"Memorization");
student.AddSkill("Spell Writing","The ability to write spells",5,"Writing");
student.AddSkill("History","The ability to write (and rewrite) history",10,"Writing");
student.AddSkill("Written Creation","The ability to write things into reality",20,"History");
student.Display(cout);

student.Display(cout);调用的两个函数如下

    void Tree::Display(ostream& out)
{
    out << "Skill Tree: " << title << "\n";
    if (this->root == NULL)
    {
        cout << "Empty\n";
        return;
    }
    else
        Display_r(out, this->root, 1);
}

void Tree::Display_r(ostream& out, Node* n, int depth)
{
    for (int i = 0; i<depth; i++)
    {
        out << "  ";
    }
    n->aSkill.Display(out);

    for (int i = 0; i<CHILD_MAX; i++)
    {
        if (n->children[i] != NULL)
        {
            Display_r(out, n->children[i], depth + 1);
        }
    }
}

如果我在AddSkill()的队列实现中注释掉一段代码,我就不会收到任何错误。

1 个答案:

答案 0 :(得分:1)

在第一个AddSkill()中,您将新节点插入树的顶部,使其成为新的根。

在第二个AddSkill()中,您打算将新节点作为父技能的子节点插入。方法似乎是:

  • 检查树中是否至少有一个节点(初始if)
  • 遍历树以查找parrent节点(while循环)
  • 如果找到父级,找到第一个插入新技能的空子项(内部for循环)

有什么问题?

您的算法存在以下几个缺陷:

  • 你在root上循环不为空。由于树在这里不是空的,并且因为你没有删除任何节点,所以这种情况将保持为真,允许无限循环。
  • 然后检查新孩子的姓名是否与父姓名相对应。我认为大多数情况下这都是假的(除此之外,你需要少一个参数)。所以这将确保循环是无止境的。
  • 稍后您假设node是当前节点,并将新child插入node个孩子。此代码未被解释。幸运的是:它将是未定义的行为,因为您已将node设置为NULL并且从未更改此值。

如何解决?

要做到这一点,您必须从node root开始,然后检查节点名称是否与parentname匹配,如果是,像你一样插入孩子。

然而,这是最后一个问题。一个相当重要的一个。算法的结构适用于链表遍历,但不适用于tree traversal。树遍历算法需要堆栈/列表来跟踪要探索的所有分支,或者需要递归方法。

这里有一些代码(抱歉,我已将char*替换为string并使用vector<Node*>代替Node*[] ), AddSkill()的辅助重载,用于执行递归搜索:

// replaces the former one that you had
void Tree::AddSkill(string name, string  desc, int level, string parentName)
{
    if (root == NULL)
    {
        cout << "Error: no nodes in tree.\n";
        return;
    }
    Skill s(name, desc, level);
    AddSkill(root, s, parentName); 
}

// auxiliary helper
void Tree::AddSkill(Node*node, Skill& s, string& parentName)
{
    if (node->sk.name == parentName) {  // if found, add the new node as childen
        Node * child = new Node(s);
        child->parent = node;
        node->children.push_back(child);
    }
    else {
        for (auto &x : node->children)   // for all the children 
            AddSkill(x, s, parentName);  // search recursively   
    }
}

这里有online demo使用共享指针而不是原始指针。