Binary Search Tree : Lowest Common Ancestor

  • + 3 comments

    Efficient Java solution - passes 100% of test cases

    From my HackerRank solutions.

    Make sure to leverage the fact that this is a binary search tree. We assume the tree has unique values.

    Runtime: O(log n) on a balanced tree
    Space Complexity: O(1)

    I solve it iteratively since recursion would take O(log n) space complexity

    static Node lca(Node n, int v1, int v2) {
        while (n != null) {
            if (n.data > v1 && n.data > v2) {
                n = n.left;
            } else if (n.data < v1 && n.data < v2) {
                n = n.right;
            } else {
                break;
            } 
        }
        return n;
    }
    

    Let me know if you have any questions.