二叉树不接受新节点
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;
}
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;
}
- 为什么线程不接受此输入?
- 函数不接受 X 参数,函数使用默认参数
- C++ boost::asio::ip::tcp::acceptor 有时不接受连接器?
- B不接受8作为输入的是什么?C++
- C++数组输入不接受一定数量的整数
- C++概念assignable_from不接受 const&-return 运算符=
- 斯堪夫不接受输入
- C++字符数组不接受超过 4 个字符的输入
- CIN不接受C++中带有空格的输入?
- 为什么C++ STL 哈希表 (unordered_map) 不接受向量作为键
- 为什么不接受具有默认分配参数的函数作为 0-arg 生成器?
- 模板接受常量,但不接受文字
- 如何在构造函数中传递 const 引用时强制编译器不接受右值
- 为什么 strtok_r() 只接受字符数组而不接受字符指针
- 语言分析的二叉树实现 - 子节点:不起作用
- C++ cout 不接受字符串或带 + 的字符串
- std::cin不接受输入
- 带有openSSL的libwebsocket服务器不接受连接
- 函数不接受 C++ 参数
- 二叉树不接受新节点