Exemple #1
0
        /// <summary>
        /// 伸展某个结点
        /// </summary>
        /// <param name="v">要提升到根结点的结点</param>
        /// <returns>返回该结点</returns>
        private BinNode <T> Splay(BinNode <T> v)
        {
            if (v == null)
            {
                return(null);
            }
            //p->parent
            //g->grandfather
            BinNode <T> p, g;

            while ((p = v.Parent) != null && (g = p.Parent) != null)
            {
                BinNode <T> gg       = g.Parent;
                bool        isLChild = g.IsLChild;
                if (v.IsLChild)
                {
                    //zig-zig
                    if (p.IsLChild)
                    {
                        g.AttachAsLChild(p.RChild);
                        p.AttachAsLChild(v.RChild);
                        p.AttachAsRChild(g);
                        v.AttachAsRChild(p);
                    }
                    //zig-zag
                    else
                    {
                        p.AttachAsLChild(v.RChild);
                        g.AttachAsRChild(v.LChild);
                        v.AttachAsLChild(g);
                        v.AttachAsRChild(p);
                    }
                }
                //zag-zag
                else if (p.IsRChild)
                {
                    g.AttachAsRChild(p.LChild);
                    p.AttachAsRChild(v.LChild);
                    p.AttachAsLChild(g);
                    v.AttachAsLChild(p);
                }
                //zag-zig
                else
                {
                    p.AttachAsRChild(v.LChild);
                    g.AttachAsLChild(v.RChild);
                    v.AttachAsRChild(g);
                    v.AttachAsLChild(p);
                }
                //如果g是根结点
                if (gg == null)
                {
                    v.Parent = null;
                }
                //如果不是
                else
                {
                    if (isLChild)
                    {
                        gg.AttachAsLChild(v);
                    }
                    else
                    {
                        gg.AttachAsRChild(v);
                    }
                }
                UpdateHeight(g);
                UpdateHeight(p);
                UpdateHeight(v);
            }
            //如果只剩下一个结点
            if ((p = v.Parent) != null)//做一次单旋
            {
                //zig
                if (v.IsLChild)
                {
                    p.AttachAsLChild(v.RChild);
                    v.AttachAsRChild(p);
                }
                //zag
                else
                {
                    p.AttachAsRChild(v.LChild);
                    v.AttachAsLChild(p);
                }
                UpdateHeight(p);
                UpdateHeight(v);
            }
            v.Parent = null;
            return(v);
        }