I've got the following code to find the lowest common ancestor (the lowest node that has both a and b as descendants):
public static Node LCA(Node root, Node a, Node b)
{
if (root == null)
return null;
if (root.IData == a.IData || root.IData == b.IData)
return root;
if (root.RightChild != null && (root.RightChild.IData == a.IData || root.RightChild.IData == b.IData))
return root;
if (root.LeftChild != null && (root.LeftChild.IData == a.IData || root.LeftChild.IData == b.IData))
return root;
if (root.IData > a.IData && root.IData > b.IData)
return LCA(root.LeftChild, a, b);
else if (root.IData < a.IData && root.IData < b.IData)
return LCA(root.RightChild, a, b);
else
return root;
}
The binary search tree is
20
/ \
8 22
/ \
4 12
/ \
10 14
Question
It is failing for the following cases:
LCA (4, 8) = 20 but should be 8.
LCA (8, 12) = 20 but should be 8
LCA (8, 23) = 20, non-existent number (23) as parameter.
Any thoughts?
Where Node is
class Node
{
public int IData {get; set;}
public Node RightChild {get; set;}
public Node LeftChild {get; set;}
}
descendant
is... – st0le