Binary Search Tree : Lowest Common Ancestor

  • + 0 comments

    Hmm I never thought to use a value test. I used a recursive inTree() function to test if a value was in a particular subtree. The running times of all test cases was 0 so the recursion didn't hurt in this case.

    https://www.hackerrank.com/challenges/binary-search-tree-lowest-common-ancestor/submissions/code/25912799

    bool inTree(node *head, int value) {
        if (head == NULL) {
            return false;
        } else if (value == head->data) {
            return true;
        } else {
            return inTree(head->left, value) || inTree(head->right, value);
        }
    }
    
    node * lca(node * root, int v1,int v2)
    {
        if (inTree(root->left, v1) && inTree(root->left, v2)) {
            return lca(root->left, v1, v2);
        } else if (inTree(root->right, v1) && inTree(root->right, v2)) {
            return lca(root->right, v1, v2);
        } else {
            return root;
        }
    }