插入到 2-3-4 树中

Inserting into a 2-3-4 tree

本文关键字:树中 2-3-4 插入      更新时间:2023-10-16

我目前正在尝试编写一个使用 2-3-4 棵树的程序,但插入函数有问题。 这是相关代码..

int main () {
    tree234 myTree;
    myTree.insert("hello");
    myTree.printTree();
    return 0;
}
//-------------tree234.cpp-------------
#include "tree234.h"
#include <string>
#include <iostream>
void tree234::insert(string input){
    int index;
    if (nullRoot == true) {
        //insert root
        initNode(root);
        root->data[0] = input;
        nullRoot = false;
        return;
    }
}
void tree234::initNode(Node* node) {
    node = new Node();
    node->pointer[0] = NULL;
    node->pointer[1] = NULL;
    node->pointer[2] = NULL;
    node->pointer[3] = NULL;
    node->data[0] = "";
    node->data[1] = "";
    node->data[2] = "";
}
//-----------tree234.h--------------
#ifndef TREE_234_H_
#define TREE_234_H_
using namespace std;
#include <iostream>
class tree234{
private:
    struct Node {
    public:
        string data[3];
        Node* pointer[4];
    };
    Node* curr;
    Node* root;
    Node* right;
    Node* newRoot;
    bool nullRoot = true;
public:
    void insert(string data);
    void initNode(Node* node);
};
#endif

它总是在第 19 行中断,并显示内存地址错误。 我尝试调试它,它在字符串文件中的第 2245 行中断(如果这有帮助的话)。这些信息并没有真正帮助我,所以也许有人可以帮助我解决这里到底出了什么问题?

存在多个问题。修复以下内容,看看它是否有效,然后...

CPP,插入:
您的 if 条件是作业。

cpp, initNode:
该函数正在更改传递的指针的副本。
调用方不会获得分配对象的任何内容。
使用对指针 (&*) 的引用或指向指针的指针
(使用匹配的函数调用和内容)作为参数。即,

void tree234::initNode(Node *& node)

首先,你有:

if (nullRoot = true) {

您可能想要的是"=="您可能应该检查编译器警告和错误。希望有帮助。:)

"

=="是比较(结果布尔值),而"="是赋值,因此您将 nullRoot 设置为 true。