简体   繁体   中英

How can I rotate Nodes in a splay tree?

The code I have is

private Node rotateLeftChild(Node n)
{
    Node o = n.left;
    n.left = o.right;
    o.right = n;
    return o;
}

When I call it to rotate a tree like this at the root:

             7
            / \
           4   8
          / \   
         1   5

it deletes the 4 and 1 and makes 5 the left root of 7. I tried just making the method a void method but that doesn't seem to work either. Am I going at this the completely wrong way?

As first, sorry for my English.

Answer to a question - why node 4 dissapears is simple. 7 have parent node (or 7 is root). When you call rotateLeftChild, parent of 7 still "thinking" that his child is 7, not 4:

真实图片

So, there are tree solutions:

  1. Make link to a parent node and update it. In the end of leftRotation, make assignment, n.Parent.Left = o or n.Parent.Right = o (if (n.Parent.Left == n) or (n.Parent.Right == n) respectively). Of course, you must update links to tree's root, when you rotate child of root.

  2. When you are adding | inserting | finding node, save all previous (parent) nodes in stack, and then after rotation you must update links to their children. Or use recursion like this:

     private Splay(Node parent, Node cur, Node n, bool canMoveUpTwice = false) { if (cur.Value > n.Value) Splay(cur, cur.Left, n, !canMoveUpTwice); else Splay(cur, cur.Right, n, !canMoveUpTwice); if (canMoveUpTwice) MoveUpTwice(); else MoveUpOnce(); if (parent.Left == cur) parent.Left = n; else parent.Right = n; if (Parent == null) tree.Root = n; }

    How to use. After adding node, you must run Splay(root, newNode). Be sure, you'll get stack overflow.

  3. You must swap values of nodes and then think that nodes have been swapped. In standart implementation of rotation we have such picture: 简单的旋转 In rotation with swaps we get this (=x means "node have value X"):交换轮换 So, we have this code

    private rotateLeftChild(Node q) { Node p = q.Left; Swap(q.Value, p.Value); A = p.Left; B = p.Right; C = q.Right; q.Left = A; q.Right = p; p.Left = B; p.Right = C; }

Be careful: the code has not been tested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM