Below is the code example for the insert code of a node into a tree.
The example is taken from http://cslibrary.stanford.edu/110/BinaryTrees.html
The problem is this: I have a basic understanding of pointers and memory, and understand the whole thing but the insert node.
here’s the node struct:
struct node {
int data;
struct node* left;
struct node* right;
}
Now, in the page I provided, it says that this method of insertion is done to avoid the pass by reference. so instead of calling insert(struct node** nodeptr, int some data); it is called this way: nodeptr = insert(data int).
so my question is. I understand the part of pointer assignment, that the pointer returned by the insert function is placed into nodeptr. supposing that nodeptr is the root of the tree, how can it affect some node which will point to the new node.
struct node* insert(struct node* node, int data)
{
// 1. If the tree is empty, return a new, single node
if (node == NULL)
{
return(newNode(data));
}
else
{
// 2. Otherwise, recur down the tree
if (data <= node->data)
{
node->left = insert(node->left, data);
}
else
{
node->right = insert(node->right, data);
}
return(node); // return the (unchanged) node pointer
}
}
It might help to walk through the code for a few inserts. So, assuming we’re calling
insertfrom functionfoo, our call tree would look something like this:After this first call to data, our tree looks something like this:
Now we make a second call to insert a new value:
Now we call
insertagain; this timenodeis the left child of the current node (which should be NULL):So the result of this second call to
insertis assigned to the left child of the current node, and our tree now looks something like this:Add another element:
And now our tree looks like
And finally: