二叉树不接受新节点

时间:2017-03-13 17:29:38

标签: c++ pointers tree binary-tree

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;
}

我有一个名为Node的结构,第一个参数是int,其他是Node指针。当我想打印root-&gt;左边它没有用时,程序在我运行时停止了。我不知道,也许我正在做一件非常奇怪的事情,期望这回事,但问题是什么?

2 个答案:

答案 0 :(得分:0)

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

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

}

答案 1 :(得分:0)

让我们逐行查看代码:

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
}

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

这是你试图做的但是以错误的方式。可以这样想:当您分配内存时,操作系统会为您提供主内存空间。它是通过给你一个&#34;参考&#34;到那个内存块,以便您可以随意使用该内存块。这就是为什么指针也被称为&#34;处理&#34;因为它们是你与内存块交互的方式。

在错误的行中,你覆盖了刚刚分配的内存的句柄。执行此操作时,您将失去对该内存块的访问权限,直到程序执行结束。这些覆盖被称为&#34;内存泄漏&#34;因为那段记忆是你问过但忘了的东西。

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

当你试图做的事情过于复杂时,就会发生这些错误 往往会发生,特别是如果你没有记忆经验。您可以简化此代码的方式是:

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,也可以通过root->left访问相同的内存块。

下面的代码就是你如何思考它。试着想一想这两者之间的区别,一旦你弄明白,指针会更有意义:

temp