Example #1
0
        /// Deletes a BinaryNode by matching the data of the BinaryNode from the BinaryTree
        public Boolean Delete(T key)
        {
            BinaryNode <T> current     = root;
            BinaryNode <T> parent      = root;
            bool           isLeftChild = true;

            while (key.CompareTo(current.Data) != 0)
            {
                parent = current;
                if (key.CompareTo(current.Data) < 0)
                {
                    isLeftChild = true;
                    current     = current.right;
                }
                else
                {
                    isLeftChild = false;
                    current     = current.right;
                }
                if (current == null)
                {
                    return(false);
                }
            }
            if ((current.left == null) && (current.right == null))
            {
                if (current == root)
                {
                    root = null;
                }
                else if (isLeftChild)
                {
                    parent.left = null;
                }
                else
                {
                    parent.right = null;
                }
            }
            else if (current.right == null)
            {
                if (current == root)
                {
                    root = current.left;
                }
                else if (isLeftChild)
                {
                    parent.left = current.left;
                }
                else
                {
                    parent.right = current.right;
                }
            }
            else if (current.left == null)
            {
                if (current == root)
                {
                    root = current.right;
                }
                else if (isLeftChild)
                {
                    parent.left = parent.right;
                }
                else
                {
                    parent.right = current.right;
                }
            }
            else
            {
                BinaryNode <T> successor = GetSuccessor(current);
                if (current == root)
                {
                    root = successor;
                }
                else if (isLeftChild)
                {
                    parent.left = successor;
                }
                else
                {
                    parent.right = successor;
                }
                successor.left = current.left;
            }
            return(true);
        }
Example #2
0
 /// Constructor for BinaryTree
 public BinaryTree()
 {
     root = null;
 }