CJCoding With Joseph
15free / daySign inCreate account

Find the Lowest Common Ancestor in a BST

Complete lowestCommonAncestor(int a, int b) so it returns the value of the lowest common ancestor of a and b, or -1 when either value is not in the tree.

Reminder: what an ancestor is. The ancestors of a node are the nodes on the path from the root down to it, and a node counts as an ancestor of itself. The lowest common ancestor of two values is the deepest node that is an ancestor of both of them: the place where their two paths down from the root split apart.

            50
          /    \
        30      70
       /  \    /  \
     20   40  60   80
         /  \
       35   45

In this tree the lowest common ancestor of 20 and 45 is 30, of 35 and 60 it is the root 50, and of 40 and 35 it is 40 itself.

The BST rule (smaller values to the left, larger values to the right) means you never have to trace both paths. Start at the root: if both values are smaller than the current node, both live on its left; if both are larger, both live on its right. The first node where neither is true is the answer.

Requirements: 1. Return -1 when a or b is not in the tree. Use the contains method the class already has; an empty tree contains nothing. 2. Walk down from root with a loop, and do not change the tree. 3. The order of a and b must not matter, and a and b may be the same value.

The Node class is provided - do not rename it and do not add public to it, because a Java source file may contain only one public class.

Do NOT write a main method.

Expected Output:

30
40
50
70
40

= newline. The output ends with a newline — print one after the last line.

Hints4 available
Topics:
Data Structures & AlgorithmsBinary Search Trees
1
Tab to indent (Esc then Tab to move on) · Ctrl+Enter to run · Shift+Alt+F to format · Ctrl+Space to expand shortcuts (sysout, psvm, fori)

Your Output

Run your code to see the output here...

Test Cases

Run your code to see test case results.