复制向量中的二叉树
Copy a binary tree in a vector
我正在尝试在 C++ 向量中复制二叉树,但我遇到了一种错误,我无法找到它的生成位置。这个i在头文件(.h)
struct NyjePeme
{
int Key;
NyjePeme *left = NULL;
NyjePeme *right = NULL;
};
class PemeKerkimi
{
private:
NyjePeme *root;
public:
PemeKerkimi();
~PemeKerkimi();
还有我在 .cpp 文件中使用的方法:
void ASCVektor(vector<int> v)
{
int i, j;
for (i = 0; i < v.size() - 1; i++)
{
for (j = i + 1; j < v.size(); j++)
{
if (v[i] > v[j])
{
int tmp = v[i];
v[i] = v[j];
v[j] = tmp;
}
}
}
}
void printVektor(vector<int> v)
{
int i;
for (i = 0; i < v.size(); i++)
{
cout << v[i] << ", ";
}
cout << endl;
}
void copyTreeinVector(NyjePeme *T, vector<int> v)
{
if (T != NULL)
{
copyTreeinVector(T->left, v);
v.push_back(T->Key);
copyTreeinVector(T->right, v);
return;
}
return;
}
NyjePeme *PemeKerkimi::TheKSmallestElement(int k)
{
vector<int> v;
coptyTreeinVector(root, v);
ASCVektor(v);
...
问题出在 copyTreeinVector() 函数中,错误消息是这样的:
进程返回 -1073741819 (0xC0000005) 并且需要一段时间才能抛出该消息。我搜索了那个错误,它是由于指针使用不当而产生的......但我无法在我的代码中找到问题
您应该通过引用在 copyTreeinVector
函数中传递向量。
而不是写作
void copyTreeinVector(NyjePeme *T, vector<int> v)
你应该写
void copyTreeinVector(NyjePeme *T, vector<int>& v)
这里有一些与该问题相关的附加链接。
What's the difference between passing by reference vs. passing by value?
https://www.educative.io/edpresso/pass-by-value-vs-pass-by-reference
我正在尝试在 C++ 向量中复制二叉树,但我遇到了一种错误,我无法找到它的生成位置。这个i在头文件(.h)
struct NyjePeme
{
int Key;
NyjePeme *left = NULL;
NyjePeme *right = NULL;
};
class PemeKerkimi
{
private:
NyjePeme *root;
public:
PemeKerkimi();
~PemeKerkimi();
还有我在 .cpp 文件中使用的方法:
void ASCVektor(vector<int> v)
{
int i, j;
for (i = 0; i < v.size() - 1; i++)
{
for (j = i + 1; j < v.size(); j++)
{
if (v[i] > v[j])
{
int tmp = v[i];
v[i] = v[j];
v[j] = tmp;
}
}
}
}
void printVektor(vector<int> v)
{
int i;
for (i = 0; i < v.size(); i++)
{
cout << v[i] << ", ";
}
cout << endl;
}
void copyTreeinVector(NyjePeme *T, vector<int> v)
{
if (T != NULL)
{
copyTreeinVector(T->left, v);
v.push_back(T->Key);
copyTreeinVector(T->right, v);
return;
}
return;
}
NyjePeme *PemeKerkimi::TheKSmallestElement(int k)
{
vector<int> v;
coptyTreeinVector(root, v);
ASCVektor(v);
...
问题出在 copyTreeinVector() 函数中,错误消息是这样的:
进程返回 -1073741819 (0xC0000005) 并且需要一段时间才能抛出该消息。我搜索了那个错误,它是由于指针使用不当而产生的......但我无法在我的代码中找到问题
您应该通过引用在 copyTreeinVector
函数中传递向量。
而不是写作
void copyTreeinVector(NyjePeme *T, vector<int> v)
你应该写
void copyTreeinVector(NyjePeme *T, vector<int>& v)
这里有一些与该问题相关的附加链接。
What's the difference between passing by reference vs. passing by value? https://www.educative.io/edpresso/pass-by-value-vs-pass-by-reference