【发布时间】:2018-10-15 15:09:45
【问题描述】:
我的任务是在向量中存储二叉树。在每个节点中存储一个 int ID、int Age 和一个字符串名称。
节点按 ID 在向量中存储和组织。
在向量中存储二叉树时,我使用算法 2i 和 2i+1 分别指示节点的左子节点和右子节点。
我已经设法创建了一个我认为满足这些条件并将节点插入向量的插入方法,但是,在尝试将这些节点插入向量之后
50 21 蒂姆
75 22 史蒂夫
我注意到它实际上并没有将这些节点插入向量中。
我放了一行插入后打印索引,发现第一次插入后,索引不再更新。
一个例子使用这个例子运行插入方法
我的 insert() 方法有问题吗?
这是我的代码。
#include "BinaryTree.h"
#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int index = 0;
struct Node
{
int ID;
int age;
string name;
Node()
{
}
Node(int id, int Age, string nm)
{
this->ID = id;
this->age = Age;
this->name = nm;
}
};
vector<Node> binaryTree(30);
BST::BST()
{
}
void BST::start()
{
int choice;
cout << "What would you like to do?" << endl;
cout << "1. Add a node to the tree" << endl;
cout << "2. Delete a node from the tree" << endl;
cout << "3. Find a node in the tree" << endl;
cout << "4. Report the contents of the tree" << endl;
cout << "5. Exit program" << endl;
cin >> choice;
if (choice == 1)
{
insert();
}
if (choice == 2)
{
Delete();
}
if (choice == 3)
{
find();
}
if (choice == 4)
{
report();
}
}
void BST::insert()
{
int ID;
int AGE;
string NAME;
int root = 1;
bool success = false;
cout << "Please enter the ID number, age and name:" << endl;
do
{
cin >> ID >> AGE >> NAME;
} while (ID < 0);
Node *tree = new Node(ID, AGE, NAME);
if (index == 0)
{
binaryTree[1] = *tree;
}
if (index > 0)
{
do
{
if (tree->ID > binaryTree.at(root).ID)
{
root = 2 * root + 1;
}
if (tree->ID < binaryTree.at(root).ID)
{
root = 2 * root;
}
if (binaryTree.at(root).ID == NULL)
{
binaryTree.at(root) = *tree;
cout << "Added!" << endl;
cout << "Vector size: " << binaryTree.size() << endl;
success = true;
}
} while (!success);
}
index++;
cout << index << endl;
delete tree;
start();
}
编辑:我意识到我未能检查索引,所以我将它从 '=' 更改为 '==' 比较以启动循环。但是,现在我得到一个 _Xout_of_range("invalid vector subscript");向量类抛出的异常
这是错误。
【问题讨论】:
-
if (index = 0) 应该是:if (index == 0)
-
@Ian4264 哦,我什至没有注意到这一点。谢谢!但现在我得到 _Xout_of_range("invalid vector
subscript");矢量类引发的错误。 -
使用调试来确定问题出在哪里。
-
insert的最后两行很奇怪,为什么要删除tree,然后下一轮再访问,为什么又要调用start,递归太多,最终会出问题导致堆栈溢出
-
@Ian4264 我不太确定如何创建一个新节点并将其添加到树中而不会导致内存泄漏。
标签: c++ vector data-structures binary-tree binary-search-tree