前言:前段时间看了伸展树,没想到一下子又忘记了,然后看了向浅的博客《伸展树c++ 实现》,决定自己也写一点自己理解过程中觉得难的地方!关于理论部分,阅读《伸展树c++ 实现》这篇博客足矣~
先看一个伸展树的例子:
伸展树的splay函数:
- void splay(const Comparable& x, BinaryNode *& root)
- {
- static BinaryNode header(x,nullnode,nullnode);
- BinaryNode * leftTreeMax,*rightTreeMin;
- header.right = header.left = nullnode; //因为static 语句只会调用一次对象的构造函数,所以必须要在这里清空左右子树
- leftTreeMax = rightTreeMin = &header;
- nullnode->element = x;
-
- for(;;)
- {
- if(x < root->element)
- {
- BinaryNode * leftChild = root->left;
- if(x < leftChild->element)
- {
- rotateWithLeftChild(root); // 该函数执行完成后,root 指向p 节点
- }
- if(root->left == nullnode)
- break;
- rightTreeMin->left = root;
- rightTreeMin = root;
- root = root->left;
- }
- else if(x > root->element)
- {
- BinaryNode * rightChild = root->right;
- if(x > rightChild->element)
- {
- rotateWithRightChild(root);
- }
- if(root->right == nullnode)
- break;
- leftTreeMax->right = root;
- leftTreeMax = root;
- root = root->right;
- }
- else
- break;
- }
- leftTreeMax->right = root->left;
- rightTreeMin->left = root->right;
- root->left = header.right;
- root->right = header.left;
- }
下面以上面的例子结合图形讲解伸展过程:
- header.right = header.left = nullnode;
- leftTreeMax = rightTreeMin = &header;
- if(x > root->element)
- {
- BinaryNode * rightChild = root->right;
- if(x > rightChild->element)
- {
- rotateWithRightChild(root);
- }
- if(root->right == nullnode)
- break;
- leftTreeMax->right = root;
- leftTreeMax = root;
- root = root->right;
- }
- if(x < root->element)
- {
- BinaryNode * leftChild = root->left;
- if(x < leftChild->element)
- {
- rotateWithLeftChild(root); // 该函数执行完成后,root 指向p 节点
- }
- if(root->left == nullnode)
- break;
-
- rightTreeMin->left = root;
- rightTreeMin = root;
- root = root->left;
- }
-
if(x > root->element)
- {
- BinaryNode * rightChild = root->right;
- if(x > rightChild->element)
- {
- rotateWithRightChild(root);
- }
- if(root->right == nullnode)
- break;
- leftTreeMax->right = root;
- leftTreeMax = root;
- root = root->right;
- }
- 1:leftTreeMax->right = root->left;
- 2:rightTreeMin->left = root->right;
- 3:root->left = header.right;
- 4:root->right = header.left;
扩展后树的形状: -
-