Binary Search Tree : Lowest Common Ancestor

  • + 11 comments

    I prefer an iterative solution to this problem rather than recursive. The code is similarly brief, and there isn't any need to load up the call stack.

    static Node lca(Node root,int v1,int v2)
    {
        Node temp = root; // not necessary, just use root, just a leftover from a different attempt.
        
        while (true) {
            if (temp.data > v1 && temp.data > v2) {
                temp = temp.left;
            } else if (temp.data < v1 && temp.data < v2) {
                temp = temp.right;
            } else {
                return temp;
            }
        }
    }