Just curious, is the reason why I don't have to use pass a pointer to pointer is that the r_insert (recursive insert) functio returns a bt_node (binary tree node) so in other words, the bt_node node list in main which is initally pointing to NULL will now point to address of new node. So had this been a void function, I would have no choice but to pass pointers to pointers (or use pass by reference). I know we even when we pass by address, we are passing the address by value so a copy of the address is used.
struct bt_node//binary tree node
{
int data;
bt_node* left;
bt_node* right;
};
//recursive insert node into BT
//Q: for an empty list, why don't I have to use ptr to ptr to update what actual front in main of BT pts to to not lose track of list
//A: I think it's b/c we are returning a ptr => we are returning address of our newly created node
bt_node* r_insert(bt_node* list, int data_)
{
bt_node* newNode = new bt_node;
newNode->data = data_;
newNode->left = NULL;
newNode->right = NULL;
if ( list == NULL )//base case: if empty list, make new node the ROOT node
{
list = newNode;//=> address of newNode is assigned to ptr list since ptrs store addresses
return list;
}
elseif (list->left == NULL && list->right == NULL )//base case: if we reached a leaf node, insert new node as this leaf node's L or R child based on value of new node
{
if ( newNode->data <= list->data )
{
list->left = newNode;
return list;
}
else
{
list->right = newNode;
return list;
}
}
else
{
if ( newNode->data <= list->data )
return r_insert(list->left, data_);//last return will return to caller main
elsereturn r_insert(list->right, data_);//last return will return to caller main
}
}
You're changing the value of bt_node* list, so you do need either pass the root node by reference or a pass a pointer to it. How else can it not be NULL?
I don't know what you mean. But what I mean is that we don't have to pass by pointer to a pointer b/c this function returns a pointer so an address, and if the tree is initally empty, I should just return the newNode for the root node to point to it in main.
I mean:
1 2 3
bt_node* root = NULL;
root = r_insert(root, 99);//so now root points to the address of new node
// this is what I mean actually and my code is wrong I realized