C++ C++;实现AVL树
我有一个树集类用c++描述一棵树:C++ C++;实现AVL树,c++,avl-tree,C++,Avl Tree,我有一个树集类用c++描述一棵树: class TreeSet { private: AVLNode * root; int count; protected: void clearRec(AVLNode*root); public: TreeSet(); ~TreeSet(); void clear(); // print out the set in ascending order friend ostream&
class TreeSet
{
private:
AVLNode * root;
int count;
protected:
void clearRec(AVLNode*root);
public:
TreeSet();
~TreeSet();
void clear();
// print out the set in ascending order
friend ostream& operator<<(ostream& os, const TreeSet& t);
int add(int val);
}
这是我在树集合中没有任何内容时添加函数的实现
int TreeSet::add(int val) {
if (root == NULL) {
AVLNode newNode(val);
root = &newNode;
count++;
}
}
主功能功能:
int main() {
TreeSet set, temp, *subSet;
ifstream ifs;
ifs.open("input.txt");
char command;
int val;
try
{
while (ifs >> command) {
switch (command) {
case 'a': // add an element to the set
ifs >> val;
set.add(val);
break;
}
}
}
}
但是当我有一个带有行的txt文件时
a 4
它不会将4打印到屏幕上。你能帮我解决这个问题吗
AVLNode newNode(val);
root = &newNode;
newNode是局部变量,您使用指向此变量的指针,但是newNode
在add
方法的末尾超出了范围,因此您有一个悬空指针。您需要通过new
运算符在堆上分配AVLNode:
root = new AVLNode(val);
newNode是局部变量,您使用指向此变量的指针,但是newNode
在add
方法的末尾超出了范围,因此您有一个悬空指针。您需要通过new
运算符在堆上分配AVLNode:
root = new AVLNode(val);
我看不到实际打印树的代码。在main函数中,问题是solved@DuyDuy如果问题解决了:请添加答案或评论,如何(让其他人向您学习-这是SO平台的目标)。THX:-)我看不到实际打印树的代码。在main函数中,问题是solved@DuyDuy如果问题解决了:请添加答案或评论,如何(让其他人向您学习-这是SO平台的目标)。THX:-)