Binary Search Tree : Lowest Common Ancestor

  • + 0 comments

    Java 7 O(n)

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