Search code examples
c++binary-treetraversal

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. It returns if there's a path between integer a to integer 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. However, the find function didn't change the pointer that was passed by reference.

//helper function to find an integer in a tree whose root node is passed in as reference

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);

}

Solution

  • Nothing in your find function assigns to the node reference, so the temp variable in hasPath is unchanged.

    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. For some reason newbies often overlook the fact that functions can return values.

    Change find to this

    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

    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.