This is a code to find least common ancestor of n1
and n2
in a binary tree
Node * lca (Node* root, int n1, int n2)
{
if (root == NULL)
return NULL;
if (root->data == n1 or root->data == n2)
return root;
Node *l = lca(root->left, n1, n2);
Node *r = lca(root->right, n1, n2);
if (l and r)
return root;
//return (l != NULL) ? l : r;
}
I took a random binary tree as shown below
1
/ \
2 3
/ \ / \
4 5 6 7
When the function call goes to node with value 5 there is no pointer to node that is returned to the caller function. So what value will be assigned to r
in that case?
I tried assuming that by default it returns a NULL pointer, so if (r == NULL)
, I tried to print a number, but I got no value in output.
I tried using the keyword undefined
like in javascript but to no avail.
It is showing error.
what does it mean to not return any value in a function that has a return type?