/* ---------------------------------------------------------- */ /* | Extra functions | */ /* ---------------------------------------------------------- */ /// <summary> /// Problem. Given the value of two nodes in a binary search tree, /// find the lowest (nearest) common ancestor. /// You may assume that both values already exist in the tree. /// /// Solution. When your target values are both less than the current node, you go left. /// When they are both greater, you go right.The first node you encounter /// that is between your target values is the lowest common ancestor. /// /// Complexity is O(log(n)). You travel down a path to the lowest common ancestor. /// Recall that traveling a path to any one node takes O(log(n)). /// </summary> public Node <T> GetLowestCommonAncestor(T value1, T value2) { Node <T> root = this.Root; while (root != null) { Interfaces.IComparable <T> value = root.Value; if (value.IsGraterThan(value1) && value.IsGraterThan(value2)) { root = root.Left; } else { if (value.IsLessThan(value1) && value.IsLessThan(value2)) { root = root.Right; } else { return(root); } } } return(null); //only if empty tree }
/* ---------------------------------------------------------- */ /* | Base functions | */ /* ---------------------------------------------------------- */ private Node <T> _InsertNode(Node <T> root, Interfaces.IComparable <T> value) { //place for adding was found if (root == null) { root = new Node <T>(null, null, value); } else if (value.IsLessThan(root.Value.Get())) { root.Left = _InsertNode(root.Left, value); } else if (value.IsGraterThan(root.Value.Get())) { root.Right = _InsertNode(root.Right, value); } else { root.Inc(); } return(root); }