Example #1
0
 public BinarySearchTree(TKey key, Comparer <TKey> comparer)
 {
     _comparer = comparer;
     Root      = new BSTreeNode <TKey, TValue> {
         Key = key
     };
 }
Example #2
0
        private void InorderTraversal(BSTreeNode <TKey, TValue> node, Action <TKey> processNode)
        {
            if (node == null)
            {
                return;
            }

            InorderTraversal(node.Left, processNode);
            processNode(node.Key);
            InorderTraversal(node.Right, processNode);
        }
Example #3
0
        public BSTreeNode <TKey, TValue> Min(BSTreeNode <TKey, TValue> root)
        {
            if (root == null)
            {
                return(null);
            }

            var node = root;

            while (node.Left != null)
            {
                node = node.Left;
            }

            return(node);
        }
Example #4
0
        public BSTreeNode <TKey, TValue> Insert(TKey key, TValue value = default)
        {
            var newNode = new BSTreeNode <TKey, TValue> {
                Key = key, Value = value
            };

            if (Root == null)
            {
                Root = newNode;
            }
            else
            {
                var trailing = Root;
                var current  = Root;
                while (current != null)
                {
                    trailing = current;
                    if (_comparer.Compare(key, current.Key) < 0)
                    {
                        current = current.Left;
                    }
                    else
                    {
                        current = current.Right;
                    }
                }

                if (_comparer.Compare(key, trailing.Key) < 0)
                {
                    trailing.Left = newNode;
                }
                else
                {
                    trailing.Right = newNode;
                }

                newNode.Parent = trailing;
            }

            return(newNode);
        }
Example #5
0
        private void Transplant(BSTreeNode <TKey, TValue> target, BSTreeNode <TKey, TValue> toPlant)
        {
            //Root
            if (target.Parent == null)
            {
                Root = toPlant;
                return;
            }

            if (target.Parent.Left == target)
            {
                target.Parent.Left = toPlant;
            }
            else
            {
                target.Parent.Right = toPlant;
            }

            if (toPlant != null)
            {
                toPlant.Parent = target.Parent;
            }
        }