[英]Binary tree doesn't accept new node
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-> left无效时,运行该程序时将其停止。 我不知道,也许我正在做一件很奇怪的事情,希望它能返回一些东西,但是出了什么问题呢?
有几件事。 您将需要检查您的节点是否等于null。 您还应该更新输出内容。
node = root;
while (node != null)
{
count << node;
node = node->left;
}
让我们逐行看一下代码:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.