Just add an iterative version of C # to search for a common ancestor in the Binary Search tree for reference:
public BinaryTreeNode BstLeastCommonAncestor(int e1, int e2) { //ensure both elements are there in the bst var n1 = this.BstFind(e1, throwIfNotFound: true); if(e1 == e2) { return n1; } this.BstFind(e2, throwIfNotFound: true); BinaryTreeNode leastCommonAcncestor = this._root; var iterativeNode = this._root; while(iterativeNode != null) { if((iterativeNode.Element > e1 ) && (iterativeNode.Element > e2)) { iterativeNode = iterativeNode.Left; } else if((iterativeNode.Element < e1) && (iterativeNode.Element < e2)) { iterativeNode = iterativeNode.Right; } else { //ie; either iterative node is equal to e1 or e2 or in between e1 and e2 return iterativeNode; } }
Where to Find is defined below
public BinaryTreeNode Find(int e, bool throwIfNotFound) { var iterativenode = this._root; while(iterativenode != null) { if(iterativenode.Element == e) { return iterativenode; } if(e < iterativenode.Element) { iterativenode = iterativenode.Left; } if(e > iterativenode.Element) { iterativenode = iterativenode.Right; } } if(throwIfNotFound) { throw new Exception(string.Format("Given element {0} is not found", e); } return null; }
And BinaryTreeNode is defined as:
class BinaryTreeNode { public int Element; public BinaryTreeNode Left; public BinaryTreeNode Right; }
** tests **
[TestMethod] public void LeastCommonAncestorTests() { int[] a = { 13, 2, 18, 1, 5, 17, 20, 3, 6, 16, 21, 4, 14, 15, 25, 22, 24 }; int[] b = { 13, 13, 13, 2, 13, 18, 13, 5, 13, 18, 13, 13, 14, 18, 25, 22}; BinarySearchTree bst = new BinarySearchTree(); foreach (int e in a) { bst.Add(e); bst.Delete(e); bst.Add(e); } for(int i = 0; i < b.Length; i++) { var n = bst.BstLeastCommonAncestor(a[i], a[i + 1]); Assert.IsTrue(n.Element == b[i]); } }