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 TreeNode
s 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) { ... }
}