[英]Why a pointer is unmutated even after passed to a function as reference?
The function "hasPath" is given a pointer to a root of a binary tree and two integers.函数“hasPath”被赋予一个指向二叉树根的指针和两个整数。 It returns if there's a path between integer a to integer b.如果整数 a 到整数 b 之间存在路径,则返回。 I thought I can use a helper function "find" to find integer "a" in the tree and change the pointer as reference, then from the tree node of "a" to find integer b.我以为我可以使用辅助函数“find”在树中找到整数“a”并将指针更改为引用,然后从“a”的树节点找到整数b。 However, the find function didn't change the pointer that was passed by reference.然而,find 函数并没有改变通过引用传递的指针。
//helper function to find an integer in a tree whose root node is passed in as reference //helper 函数在树中查找一个整数,其根节点作为引用传入
bool find(BinaryTreeNode*&node, int a){
if (node==nullptr){
return false;
} else if (node->data==a){
return true;
}else {
return find(node->left, a) or find(node->right, a);
}
}
//a function returns if there is a path between integer a and b in the
//binary tree passed in as root node
bool hasPath(BinaryTreeNode* node, int a, int b){
if (node==nullptr) return false;
BinaryTreeNode*temp = node;
return find(temp,a) //the pointer temp should be changed, but didn't
and
find(temp, b);
}
Nothing in your find
function assigns to the node
reference, so the temp
variable in hasPath
is unchanged. find
函数中没有任何内容分配给node
引用,因此hasPath
的temp
变量hasPath
更改。
To make this work you should change hasPath
so that it returns the node you are interested in. There's no need to use a reference.要完成这项工作,您应该更改hasPath
以便它返回您感兴趣的节点。无需使用引用。 For some reason newbies often overlook the fact that functions can return values.由于某些原因,新手经常忽略函数可以返回值的事实。
Change find
to this将find
更改为此
BinaryTreeNode* find(BinaryTreeNode* node, int a)
{
if (node == nullptr)
{
return nullptr; // return nullptr for not found
}
else if (node->data == a)
{
return node; // found the node
}
else
{
// recurse left or right
BinaryTreeNode* temp = find(node->left, a);
return temp ? temp : find(node->right, a);
}
}
Then change hasPath
to use the returned node然后更改hasPath
以使用返回的节点
bool hasPath(BinaryTreeNode* node, int a, int b)
{
if (node == nullptr)
return false;
node = find(node, a);
if (node == nullptr)
return false;
node = find(node, b);
if (node == nullptr)
return false;
return true;
}
BTW I'm not making any comment on the validity of your algorithm, but I believe the code above is what you were trying to implement.顺便说一句,我不会对您算法的有效性发表任何评论,但我相信上面的代码就是您想要实现的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.