二叉树不接受新节点

Binary tree doesn't accept new node

本文关键字:节点 不接受 新节点 二叉树      更新时间:2023-10-16
int main(){
Node *root , *temp , *temp_before;
root = new Node(0 , NULL , NULL , NULL);
temp_before = root;
temp = temp_before->left;
temp = new Node(5 , NULL , NULL , NULL);
temp = root->left;
cout<<temp->val;
}

i有一个名为节点的结构,第一个参数是int,其他是节点指针。当我想打印root->左它不起作用时,该程序在运行时停止了。我不知道,也许我期望它回来一些问题,但是我正在做一个非常奇怪的事情,但是有什么问题?

让我们逐行查看代码:

struct Node {
    int val;
    Node* left;
    Node* right;
    Node* parent;
    Node(int value, Node* left, Node* right, Node* parent): val(value), left(left), right(right), parent(parent){}
};
void main() {
    Node *root, *temp, *temp_before;
    root = new Node(0, NULL, NULL, NULL); // root points to the newly allocated memory
    temp_before = root; //temp_before also points to that memory
    temp = temp_before->left; // temp points to the left of root, which is null
    // NOTE: at this point, temp isn't connected to the tree, even if you allocate memory with it.
    // You only have pointers ("handles") for those memory blocks but you haven't combined them together yet.
    temp = new Node(5, NULL, NULL, NULL); // This allocated memory for the memory address pointed by temp
    // temp = root->left; //error
    root->left = temp; //correct one
    // Now root->left points to the memory block you allocated with temp
}

使用指针分配内存时,指针仅指向该内存块。除非您手动将它们连接在一起,否则它们不会成为连接的结构。

那是您要做的,但以错误的方式进行。想一想:当您分配内存时,操作系统为您提供了主内存的空间。它通过向您提供对该内存块的"引用"来做到这一点,以便您可以根据需要使用该内存块。这就是为什么指针也称为"手柄",因为它们是您与内存块互动的方式。

在错误的行中,您将手柄覆盖到刚分配的内存中。当您这样做时,您将失去对该内存块的访问权限,直到程序执行结束为止。这些替代被称为"内存泄漏",因为您问的是记忆的块,但忘记了。

执行temp = root->left;时,它会用另一个指针覆盖指针(在这种情况下,指向NULL),当您尝试打印它时,它会给您一个称为null pointer exception的错误,从名称可以清楚地看到它问题:)

当您夸大您要做的事情时,这些错误会发生往往会发生,尤其是如果您没有记忆的经验。您可以简化此代码的方式是:

void main() {
    Node* root = new Node(0, NULL, NULL, NULL); // Allocate root
    root->left = new Node(5, NULL, NULL, NULL); // This line means "add a new node to the left of my root"
    std::cout << root->val << std::endl;
    std::cout << root->left->val << std::endl;
}

如果您在上述实施中遇到困难,请这样考虑:

Node* temp = new Node(5, NULL, NULL, NULL);
root->left = temp;

此代码与main函数中的代码相同。这样想:您是在分配一个内存块并使用句柄temp访问它。之后,您是将将信息处理到根的左节点指针的分配。这样,即使您无法访问temp,您也可以通过root->left访问相同的内存块。

下面的代码是您如何思考。尝试考虑这两个之间的区别,一旦您弄清楚,指针将变得更有意义:

Node* temp = root->left;
temp = new Node(5, NULL, NULL, NULL);

有几件事。您需要检查您的节点是否等于null。您还应该更新输出的内容。

node = root;
while (node != null) 
{
    count << node;
    node = node->left;
}