![](/img/trans.png)
[英]find a node in a tree and replace with a new node with update private members
[英]Error with Node of Tree Class, perhaps because of private Node 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);
}
然后,您嘗試添加左或右子節點,您的recInsert
函數將收到指向節點的指針,而不是指向指針或指針的指針。 因此,您要更改功能參數而不是子節點。 快速解決方法:
void recInsert(string a, TreeNode<string>*& current) {
// The same code
}
以下是一些背景知識: 指向指針的指針和指向指針的引用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.