Reputation: 719
I was reading the following article. Add greater values of every node
So my doubt after the function void modifyBSTUtil(struct node *root, int *sum)
returns , why the changes made by it persist in the tree.
1.We are not using double pointers
2.Nor is the root global
3.We are not returning the address
Can anyone explain why this happens??
Code
void modifyBSTUtil(struct node *root, int *sum)
{
// Base Case
if (root == NULL) return;
// Recur for right subtree
modifyBSTUtil(root->right, sum);
// Now *sum has sum of nodes in right subtree, add
// root->data to sum and update root->data
*sum = *sum + root->data;
root->data = *sum;
// Recur for left subtree
modifyBSTUtil(root->left, sum);
}
Call : modifyBSTUtil(root, &sum)
Insert Function
struct node* insert(struct node* node, int data)
{
/* If the tree is empty, return a new node */
if (node == NULL) return newNode(data);
/* Otherwise, recur down the tree */
if (data <= node->data)
node->left = insert(node->left, data);
else
node->right = insert(node->right, data);
/* return the (unchanged) node pointer */
return node;
}
We need to return the address in case of insert function to make changes permanent and why not return here??
Upvotes: 1
Views: 66
Reputation: 19736
There's nothing sacred in a function that prevents is from making a persistent effect on the outside world, the only restriction is the arguments it receives may limit what data it may access.
In this case, it's getting a pointer to a node, and uses it to access the node and change the data there. It's not changing the pointer itself since that is given by value (i.e. - the pointer value is copied, so changing it won't be visible outside), but the pointer value is enough to access the memory of that node and change the values stored there. Note that accessing the node itself can allow you to change the pointers there, and therefore change the tree structure anywhere below that node.
Upvotes: 0
Reputation: 23560
This works because in this example the linking between the nodes is not changed. Only the values they store (->data
).
Upvotes: 3