这是极客对极客的一个例子。最后一个例子是root->left->left = new Node(4); --我想知道左节点如何保留它的旧值,并且能够使用相同的struct变量连接到一个新值。每次“Node()”是否被称为它创建了另一个内存块?我很困惑。
using namespace std;
struct Node {
int data;
struct Node* left;
struct Node* right;
// val is the key or the value that
// has to be added to the data part
Node(int val)
{
data = val;
// Left and right child for node
// will be initialized to null
left = NULL;
right = NULL;
}
};
int main()
{
/*create root*/
struct Node* root = new Node(1);
/* following is the tree after above statement
1
/ \
NULL NULL
*/
root->left = new Node(2);
root->right = new Node(3);
/* 2 and 3 become left and right children of 1
1
/ \
2 3
/ \ / \
NULL NULL NULL NULL
*/
root->left->left = new Node(4);
/* 4 becomes left child of 2
1
/ \
2 3
/ \ / \
4 NULL NULL NULL
/ \
NULL NULL
*/
return 0;
}发布于 2021-05-29 01:07:00
root->left = new Node(2);和root->left->left = new Node(4);都会在内存中创建新的节点对象,所以您需要考虑的是
每次都会调用“Node()”来创建另一个内存块或什么的?
有点准确。
最初,root是一个Node对象,其数据值为1,左值为空。它的左指针指向什么都没有。语句root->left = new Node(2);设置指向新节点地址的根左指针。这个新节点的数据值为2,左值为NULL。假设这个新节点有一个名称,它的名称是A。表达式root->left->left从左到右计算,所以root->left是节点A,因此表达式变成A->left。A->left当前为空。执行root->left->left = new Node(4);之后,A的左指针现在指向一个数据值为4的新节点。
https://stackoverflow.com/questions/67746832
复制相似问题