码迷,mamicode.com
首页 > 其他好文 > 详细

cs61b lab14

时间:2017-08-03 17:37:42      阅读:102      评论:0      收藏:0      [点我收藏+]

标签:lin   tree   code   into   return   logs   void   play   bsp   

实现splayTree,不过感觉大头都已经写好了,难度不算太大。

part1:zig-zig,类似zig-zag,不过是先要rotate node.parent再rotate node。

private void zigZig(BinaryTreeNode node) {
      
    if(node==node.parent.leftChild){
        rotateRight(node.parent);
        rotateRight(node);
    }
    else{
        rotateLeft(node.parent);
        rotateLeft(node);
    }
      }

part2:splaynode:

private void splayNode(BinaryTreeNode node) {
        while (node.parent != null) {
          if(node.parent.parent!=null){
              if(node.parent.parent.leftChild==node.parent&&node.parent.leftChild==node||node.parent.parent.rightChild==node.parent&&node.parent.rightChild==node){
                  zigZig(node);
              }
              else {
                  zigZag(node);
              }
          }
          else {
              zig(node);
          }
        }
        
        root = node;
    }

运行结果:

PART I:  Testing zigZig()

Inserting 1G, 3O, 2O, 5J, 4D, 7B, 6O into Tree 1.
Tree 1 is:  (((((1G)2O)3O)4D)5J)6O(7B)
Skipping the rest of Part I.

PART II:  Testing splayNode()

Calling splayNode() on the unbalanced tree:

Inserting 10A, 9B, 8C, 7D, 6E, 5F, 4G, 3H, 2I, 1J
tree is:  1J(2I(3H(4G(5F(6E(7D(8C(9B(10A)))))))))
Calling find(10)
  returned A.
The tree should be better balanced now: (1J((2I)3H((4G)5F((6E)7D((8C)9B)))))10A

Some find() operations on a new tree to test splayNode():

Inserting 3A, 7B, 4C, 2D, 9E, 1F
Tree 2 is:  1F((2D(3A((4C)7B)))9E)
Calling find(7)
  returned B.
Tree 2 is:  (1F((2D)3A(4C)))7B(9E)
Calling find(4)
  returned C.
Tree 2 is:  ((1F(2D))3A)4C(7B(9E))

 

cs61b lab14

标签:lin   tree   code   into   return   logs   void   play   bsp   

原文地址:http://www.cnblogs.com/lyz1995/p/7280809.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!