我正在尝试将一个字符串传递给二叉树的构造函数,并让第一个字符成为根。但是,无论出于何种原因,我都无法将第一个值分配给 root 的值,而是整个程序崩溃了。有人知道为什么会崩溃吗?
class PrefixTree
{
private:
struct TreeNode
{
char character;
TreeNode * left;
TreeNode * right;
};
TreeNode* root;
public:
PrefixTree()
{
root = NULL;
}
PrefixTree(string value)
{
cout<<"wait";
if (value[0] == '*')
{
cout << "Out 1"<<endl;
root->character = value;
cout << "Out 2"<<endl;
root->left = NULL;
cout << "Out 3"<<endl;
root->right = NULL;
}
}
和主要:
int main()
{
PrefixTree n("*abc");
return 0;
}
最佳答案
您需要为 root
分配内存,但您没有这样做。
PrefixTree(string value)
{
root = new TreeNode;
// . . .
}
此外,不要忘记在析构函数中删除
它(并正确处理拷贝)。
关于c++ - 二叉树,构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21806879/