为什么我的节点在我设置后被设置为 nullptr = 新节点?

Why is my node set as a nullptr after I have set it = new Node?

本文关键字:设置 节点 新节点 nullptr 我的 为什么      更新时间:2023-10-16

我已经将节点指针初始化为 nullptr,并将其作为引用传递给帮助程序函数。在辅助函数中,我将以前为 nullptr 的指针设置为等于新指针。但是,函数结束后,它会再次设置为 nullptr。

void helper(vector<int>& nums, int start, int end, TreeNode* root){
if(start >= end) return;
root = new TreeNode;
int median = (start + end) / 2;
root -> val = nums[median];
helper(nums, start, median - 1, root -> left);
helper(nums, median + 1, end, root -> right);
}
TreeNode* sortedArrayToBST(vector<int>& nums) {
TreeNode* root = nullptr;
helper(nums, 0, nums.size() - 1, root);
return root;
}
将其

作为引用传递到帮助程序函数中

不,指针由值本身传递。参数root只是参数的副本,函数内对指针本身的任何修改都与参数无关。

将其更改为按引用传递:

void helper(vector<int>& nums, int start, int end, TreeNode*& root){
//                                                          ^
if(start >= end) return;
root = new TreeNode;
int median = (start + end) / 2;
root -> val = nums[median];
helper(nums, start, median - 1, root -> left);
helper(nums, median + 1, end, root -> right);
}

参数按C++中的值传递。当你有

void foo(sometype x) {
x = something;    // modifies the local x
}

然后,x的修改将仅在函数内部可见,因为它是在函数本地x上进行的。指针也不例外。如果要修改原始参数,则需要通过引用传递:

void bar(sometype& x) {
x = something;   // modifies the object refered to by x
}

TL;您需要的灾难恢复

void helper(vector<int>& nums, int start, int end, TreeNode*& root){
....

PS:我想你的困惑源于这样一个事实,即指针允许您修改点。指针的副本指向同一对象,因此...

void moo(int* x) {
*x = 42;        // modifies the int pointed to by x
}
int a = 0;
int* p = &a;
moo(p);             // x above is a copy of p

不过,在一般情况下,应该首选引用(除非nullptr是一个有效的参数(。此外,您要修改指针而不是脚尖。