【问题标题】:Attempting to read in a string to put into a binary tree尝试读入字符串以放入二叉树
【发布时间】:2018-02-07 18:34:11
【问题描述】:

我正在尝试获取一个字符串,然后将其操作成二叉树。唯一的问题是,我很难真正阅读字符串。我知道在 c++ 中每个单独的字符都是一个字符,而不是一个字符串,但我不知道如何通过字符串递归来获取每个字符(我希望这是有道理的)。我试图将第一个字符作为根放入我的构造函数中,然后进入我的构建树函数,然后继续向下填充它。有人有什么想法吗?


class PrefixTree
{
    private:
        struct TreeNode
        {
            char character;
            TreeNode * left;
            TreeNode * right;
        };
        TreeNode* root = new TreeNode;
    public:

    PrefixTree(string value)
    {
        if (value == '*')
        {
            root->character = value;

        }
        buildTree(root, value);
    }
    TreeNode* buildTree(TreeNode* node, string value)
    {
        TreeNode* currentNode = new TreeNode;
        currentNode = node;

        if (currentNode->character == '*' && currentNode->left == NULL)
        {
            currentNode->left = buildTree(currentNode->right,value);
            return currentNode;
        }
        else if (currentNode->character == '*' && currentNode->right == NULL)
        {
            currentNode->right = buildTree(currentNode->right,value);
            return currentNode;
        }
        else
        {
            return currentNode;
        }
    }      

以及我如何在 main 中调用构造函数:

  PrefixTree n("*ab");

【问题讨论】:

  • 'TreeNode* currentNode = new TreeNode;当前节点 = 节点;'在 buildTree 开始时一定是错误的 - 你首先分配一个 TreeNode,然后用 node 覆盖指针,从而丢弃你新分配的内存

标签: c++ string tree binary-tree


【解决方案1】:

您可以对字符串使用 [] 运算符来获取单个字符。

例如:

string a = "hello";
cout << a[0];

将打印“h”,a 的第一个字符。

我建议,在您的递归函数中,使用 [] 运算符获取一个字符,然后使用 .substr() 函数对部分字符串进行递归。

【讨论】:

    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 2021-12-25
    • 2013-04-02
    • 1970-01-01
    • 2023-03-15
    • 2015-04-11
    • 2021-10-01
    • 2022-01-18
    相关资源
    最近更新 更多