【问题标题】:Error with Node of Tree Class, perhaps because of private Node members树类节点出错,可能是因为私有节点成员
【发布时间】:2016-09-14 14:55:55
【问题描述】:

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

#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);
}

【问题讨论】:

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


    【解决方案1】:

    然后您尝试添加左或右子节点,您的recInsert 函数接收指向节点的指针,而不是指向指针的指针或对指针的引用。因此,您正在更改函数参数而不是子节点。这是一个快速修复:

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

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

    【讨论】:

      猜你喜欢
      • 2016-07-19
      • 1970-01-01
      • 1970-01-01
      • 2015-03-02
      • 1970-01-01
      • 2014-08-29
      • 2021-12-20
      • 1970-01-01
      • 2016-12-18
      相关资源
      最近更新 更多