Example #1
0
        public TreeNode Remove()
        {
            if (Left == null && Right == null)
            {
                if (Parent == null)
                {
                    return(null);
                }

                if (Parent.Left == this)
                {
                    Parent.Left = null;
                }
                else
                {
                    Parent.Right = null;
                }

                Parent.UpdateHeight();
                return(Parent.BalanceTree());
            }

            if ((Left == null) ^ (Right == null))
            {
                if (Left != null)
                {
                    if (Parent != null)
                    {
                        if (Parent.Left == this)
                        {
                            Parent.Left = Left;
                        }
                        else
                        {
                            Parent.Right = Left;
                        }

                        Parent.UpdateHeight();
                    }

                    Left.Parent = Parent;
                    return(Left.BalanceTree());
                }

                if (Parent != null)
                {
                    if (Parent.Left == this)
                    {
                        Parent.Left = Right;
                    }
                    else
                    {
                        Parent.Right = Right;
                    }

                    Parent.UpdateHeight();
                }

                Right.Parent = Parent;
                return(Right.BalanceTree());
            }


            //Two child
            if (Left != null && Right != null)
            {
                var prev = Previous();
                prev.Remove();
                Key = prev.Key;
            }

            return(BalanceTree());
        }