二叉树,构造函数

Binary Tree, constructor

本文关键字:构造函数 二叉树      更新时间:2023-10-16

我正在尝试将字符串传递给二叉树的构造函数,并使第一个字符成为根。但是,无论出于何种原因,我都无法将第一个值分配给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;
   // . . .
}

另外,不要忘记在析构函数中delete它(并正确处理副本)。