I need to find the lowest common node in two BST. I'm having trouble finding out how to do it. I should use recursion, not storing values in arrays.
I tried to implement inorder search. But it's not working as it returns nothing.
Here's my insert function:
tree *insert(tree* node, int data){
if (node == NULL) {
node = malloc(sizeof(node));
node->data = data;
node->left = node->right = NULL;
}
else if (data < node->data)
node->left = insert(node->left, data);
else if (data > node->data)
node->right = insert(node->right, data);
return node;
}
My search function.
tree *search (tree* node, int data){
if (node == NULL || node->data == data){
return node;
}
if (data > node->data){
return search(node->right, data);
}
return search(node->left, data);
}
and my lowest_common function:
int lowest_common (tree *t1, tree *t2){
if(t1 == NULL || t2 == NULL){
return -1;
}
if(t1->data == t2->data){
return 1;
}
else if (t1->data != t2->data){
lowest_common(t1->left, t2);
search(t2, t1->data);
lowest_common(t1->right, t2);
}
printf("test");
return 1;
}
after inserting inputs in both trees, I'd call lowest_common(t1, t2)
it should return -1 if there are no common nodes and 1 if there is a lowest node in common. But it returns nothing. Any ideas?