树类节点出错,可能是因为私有节点成员

时间:2016-05-18 08:32:21

标签: c++ tree binary-tree private members

所以我一直在测试树节点类并遇到了一些错误。我认为这是因为我使用私有Node成员并使用访问器功能来访问它们。使用del函数,我尝试在PostOrder中遍历时打印和删除测试树,但除了" root"之外没有输出。

#include <iostream>
#include <string>
using namespace std;

#ifndef TREENODE_H
#define TREENODE_H
template <class T>
class TreeNode
{
private:
    typedef TreeNode<T>* nodePtr;
    T data;
    nodePtr lst;
    nodePtr rst;
public:
    TreeNode()
    {
        lst = NULL;
        rst = NULL;
    };
    TreeNode(T d)
    {
        data = d;
        lst = NULL;
        rst = NULL;
    };
    TreeNode(const TreeNode<T>* other)
    {
        data = other.data;
        lst = other.lst;
        rst = other.rst;
    };

    void setData(T d)
    {
        data = d;
    }

    T getData()
    {
        return data;
    }

    void setLeft(nodePtr l)
    {
        lst = l;
    }

    void setRight(nodePtr r)
    {
        rst = r;
    }

    nodePtr getLeft()
    {
        return lst;
    }

    nodePtr getRight()
    {
        return rst;
    }

    ~TreeNode()
    {
        cout << "gone: " << data;
    }
};
#endif

#include <iostream>
#include <string>
#include "TreeNode.cpp"

using namespace std;



void recInsert(string a, TreeNode<string>* current)
{
    if (current == NULL)
    {
        current = new TreeNode < string > ;
        current->setData(a);
        current->setLeft(NULL);
        current->setRight(NULL);
    }
    else if (a <= current->getData())
        recInsert(a, current->getLeft());
    else recInsert(a, current->getRight());
};

void del(TreeNode < string > *current)
{
    if (current != NULL)
    {
        del(current->getLeft());
        del(current->getRight());
        cout << current->getData();
        delete current;
    }
}

int main()
{
    TreeNode<string>* a;
    a = new TreeNode <string>;
    a->setData("hi");
    recInsert("ho", a);
    recInsert("bo", a);
    recInsert("ao", a);
    recInsert("lo", a);
    del(a);
}

1 个答案:

答案 0 :(得分:0)

然后,您尝试添加左侧或右侧子节点,recInsert函数接收指向节点的指针,而不是指向指针或指针的指针。因此,您要更改函数参数而不是子节点。这是一个快速解决方法:

void recInsert(string a, TreeNode<string>*& current) {
    // The same code
}

这里有一些背景阅读: Pointer to Pointer and Reference to Pointer