public void Remove(int key)
        {
            if (key < _key)
            {
                _leftChild?.Remove(key);
                return;
            }

            if (key > _key)
            {
                _rightChild?.Remove(key);
                return;
            }

            bool isThisALeftChild = this == _parent.GetChild(true);

            // No children case

            if (GetChild(true) == null && GetChild(false) == null)
            {
                if (isThisALeftChild)
                {
                    _parent.SetChild(null, true);
                }
                else
                {
                    _parent.SetChild(null, false);
                }

                return;
            }

            // One child case

            if (GetChild(true) == null || GetChild(false) == null)
            {
                if (GetChild(true) != null)
                {
                    _parent.SetChild(GetChild(true), isThisALeftChild);
                    GetChild(true).SetParent(_parent);
                    return;
                }

                if (GetChild(false) != null)
                {
                    _parent.SetChild(GetChild(false), isThisALeftChild);
                    GetChild(false).SetParent(_parent);
                    return;
                }
            }

            // Both children case

            // Finding the successor
            BinaryTreeNode successorNode = _rightChild;

            while (successorNode.GetChild(true) != null)
            {
                successorNode = successorNode.GetChild(true);
            }

            CopyFrom(successorNode);

            // If the successor has no children
            if (successorNode.GetChild(true) == null && successorNode.GetChild(false) == null)
            {
                if (successorNode == _rightChild)
                {
                    SetChild(null, false);
                }
                else
                {
                    successorNode.GetParent().SetChild(null, true);
                }

                return;
            }

            // The successor has a right child
            if (successorNode == _rightChild)
            {
                SetChild(successorNode.GetChild(false), false);
            }
            else
            {
                successorNode.GetParent().SetChild(successorNode.GetChild(false), true);
                successorNode.GetChild(false).SetParent(successorNode.GetParent());
            }
        }
 private void CopyFrom(BinaryTreeNode node)
 {
     SetKey(node.GetKey());
     SetValue(node.GetValue());
 }
Beispiel #3
0
 public void CreateChild(int key, string value, bool isLeft)
 {
     _root = new BinaryTreeNode(key, value, null);
 }
Beispiel #4
0
 public void SetChild(BinaryTreeNode newChild, bool isLeft)
 {
     _root = newChild;
 }
Beispiel #5
0
 public BinaryTree()
 {
     _root = null;
 }