logo CodeStepByStep logo

lowestCommonAncestor

Language/Type: Java binary trees

Write a method named lowestCommonAncestor that returns the value of the lowest common ancestor between two values in a binary tree. Your method accepts as its parameters a TreeNode referring to the root of the tree along with two integer parameters a and b. You must return the integer value of the node that is their lowest common ancestor. For example, if a variable tree stores a reference to the root of the following tree:

(3 (5 (6) (2 (7) (4))) (1 (9 (8))))

Then the call of lowestCommonAncestor(tree, 4, 6) should return 5. A node is considered to be its own ancestor for this problem, so the call of lowestCommonAncestor(tree, 5, 4) should also return 5. If the tree does not contain both a and b, return 0. You may assume that the values in the tree are unique.

Assume that you are interacting with TreeNodes as defined below:

public class TreeNode {
    public int data;
    public TreeNode left;
    public TreeNode right;
    
    public TreeNode() { ... }
    public TreeNode(int data) { ... }
    public TreeNode(int data, TreeNode left, TreeNode right) { ... }
}
Method: Write a Java method as described, not a complete program or class.

You must log in before you can solve this problem.

Log In

Need help?

Stuck on an exercise? Contact your TA or instructor.

If something seems wrong with our site, please

Is there a problem? Contact us.