1

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?

akemi
  • 21
  • 2
  • If you're having trouble finding the algorithm, I think there are a LOT of resources out there. This is one example that is decent imo: [link](https://www.youtube.com/watch?v=F-_1sbnPbWQ) If you're having trouble with your specific code (which kind of seems like homework to me, for what it's worth), what have you tried? How have you debugged it? What are your test cases like? We can't help you without complete information. – Ricky Mutschlechner Apr 05 '19 at 19:25

0 Answers0