Example #1
0
        public override BinNode <T> Insert(T e)
        {
            BinNode <T> x = Search(e);

            if (x != null)
            {
                return(x);
            }
            //空树,第一次插入节点
            if (Hot == null)
            {
                Root = new BinNode <T>(e);
                Size++;
                UpdateHeight(Root);
            }
            else
            {
                if (Lt(e, Hot.Data))
                {
                    x = Hot.InsertAsLc(e);
                }
                else
                {
                    x = Hot.InsertAsRc(e);
                }
                Size++;
                UpdateHeightAbove(x);
            }

            //一直到根节点
            for (BinNode <T> g = Hot; g != null; g = g.Parent)
            {
                if (!g.AvlBalanced())
                {
                    bool isLchild = g.IsLChild;
                    bool isRoot   = g == Root;
                    var  y        = RotateAt(TallerChild(TallerChild(g)));
                    if (!isRoot)
                    {
                        if (isLchild)
                        {
                            y.Parent.LChild = y;
                        }
                        else
                        {
                            y.Parent.RChild = y;
                        }
                    }
                    break;
                }
                else
                {
                    UpdateHeight(g);
                }
            }
            return(x);
        }
Example #2
0
        public override bool Remove(T e)
        {
            BinNode <T> x = Search(e);

            if (x == null)
            {
                return(false);
            }
            RemoveAt(x);
            Size--;
            for (BinNode <T> g = Hot; g != null; g = g.Parent)
            {
                if (!g.AvlBalanced())
                {
                    bool isLeft = g.IsLChild;
                    bool isRoot = g.IsRoot;
                    var  parent = g.Parent;
                    var  y      = RotateAt(TallerChild(TallerChild(g)));
                    if (isRoot)
                    {
                        Root = y;
                    }
                    else
                    {
                        if (isLeft)
                        {
                            g.Parent.LChild = y;
                        }
                        else
                        {
                            g.Parent.RChild = y;
                        }
                    }
                    g.Parent = y;
                    y.Parent = parent;
                }
                UpdateHeight(g);
            }
            return(true);
        }