So I'm writing some binary search tree functions in C (here are the node structure and insert function which work perfectly):
typedef struct searchTreeNode {
int data;
struct searchTreeNode *left;
struct searchTreeNode *right;
} STNode;
void insert(STNode **proot, int data) {
STNode *node = *proot;
if (!node) {
*proot = newNode(data);
return ;
}
if (data <= node -> data) insert(&(node -> left), data);
else insert(&(node -> right), data);
}
And I found that the following recursive function for finding the max value of the tree works just fine even though just the last recursive call is actually returning an integer:
int max(STNode *node) {
if (!node) return 0;
if (!(node -> right)) return node -> data;
max(node -> right);
}
This means, if I am not mistaken, that it does exactly the same as this:
int max(STNode *node) {
if (!node) return 0;
if (!(node -> right)) return node -> data;
return max(node -> right);
}
Where the function now returns the value it gets from the next recursion call.
Is this a known behavior where the function returns the last returned value or am I missing something?
Here is my main function with some random numbers:
int main() {
STNode *root = NULL;
insert(&root, 10);
insert(&root, 13);
insert(&root, 14);
insert(&root, 124);
insert(&root, 1);
insert(&root, 8);
insert(&root, 3);
printf("Max value: %d\n", max(root));
return 0;
}