public T LowestCommonAncestor(T one, T two) { // we have several choices, either one of the values is the current (enabled) node, in which case the LCA is this value if (_enabled && (_value.Equals(one) || _value.Equals(two))) { return(_value); } // if we've got here, then we know neither one nor two are equal to my value, unless this node is disabled // else if both are to one side, then the LCA (if it exists) is that side if (_left != null && _value.CompareTo(one) >= 0 && _value.CompareTo(two) >= 0) { return(_left.LowestCommonAncestor(one, two)); } if (_right != null && _value.CompareTo(one) < 0 && _value.CompareTo(two) < 0) { return(_right.LowestCommonAncestor(one, two)); } // else if they must be either side, then they need to be present on both sides IList <T> both = new List <T> { one, two }; if (_left.Present(one) && _right.Present(two)) { return(_value); } // otherwise there isn't one (i.e. either it would be this one and it is null or one or other of the values isn't present in the tree) return(default(T)); }
public void TestLCA() { Assert.AreEqual(8, tree.LowestCommonAncestor(5, 9)); }