コード例 #1
0
            public void DeleteNodeByNumber(int number)
            {
                Node node = SearchNodeByNumber(number);

                if (node == null)
                {
                    return;
                }

                if (node.Left == null && node.Right == null)
                {
                    if (node.Parrent != null)
                    {
                        if (node.Parrent.Left == node)
                        {
                            node.Parrent.Left = null;
                        }
                        else
                        {
                            node.Parrent.Right = null;
                        }
                    }
                    else
                    {
                        root = null;
                    }
                }
                else if (node.Left != null && node.Right != null)
                {
                    Node current = node.Right;

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

                    Node insertableNode = (Node)current.Clone();

                    insertableNode.Left  = node.Left;
                    insertableNode.Right = node.Right;

                    // Вставка узла вместо удаляемого
                    if (node.Parrent != null)
                    {
                        if (node.Parrent.Left == node)
                        {
                            node.Parrent.Left = insertableNode;
                        }
                        else
                        {
                            node.Parrent.Right = insertableNode;
                        }
                    }
                    else
                    {
                        root = insertableNode;
                    }

                    // Удаление вставляемого узла
                    if (insertableNode.Left == current)
                    {
                        insertableNode.Left = current.Right;
                    }
                    else if (insertableNode.Right == current)
                    {
                        insertableNode.Right = current.Right;
                    }
                    else if (current.Parrent.Left == current)
                    {
                        current.Parrent.Left = current.Right;
                    }
                    else if (current.Parrent.Right == current)
                    {
                        current.Parrent.Right = current.Right;
                    }
                }
                else
                {
                    if (node.Parrent.Left == node)
                    {
                        node.Parrent.Left = node.Left ?? node.Right;
                    }
                    else
                    {
                        node.Parrent.Right = node.Left ?? node.Right;
                    }
                }
            }