Exemplo n.º 1
0
        /* ---------------------------------------------------------- */
        /* |                   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
        }
Exemplo n.º 2
0
 public Node(Node <T> left, Node <T> right, Interfaces.IComparable <T> value)
 {
     this.Left    = left;
     this.Right   = right;
     this.Value   = value;
     this.Counter = 1;
 }
Exemplo n.º 3
0
 /* ---------------------------------------------------------- */
 /* |                    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);
 }
Exemplo n.º 4
0
 public Node <T> InsertNodeNonRecursively(Node <T> root, Interfaces.IComparable <T> value)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 5
0
 public bool InsertNode(Interfaces.IComparable <T> value)
 {
     this.Root = _InsertNode(this.Root, value);
     return(true);
 }