`
evasiu
  • 浏览: 171214 次
  • 性别: Icon_minigender_2
  • 来自: 广州
博客专栏
Fa47b089-e026-399c-b770-017349f619d5
TCP/IP详解卷一>阅读...
浏览量:12646
社区版块
存档分类
最新评论

数据结构 -- 二叉树(BST, AVLTree, RBTree, SplayTree)

 
阅读更多

在《基于树的索引结构介绍》(http://philoscience.iteye.com/admin/blogs/1112759)中提到了二分查找树及其改进版本AVL树(平衡二叉树)。二分查找树比较简单,但是很容易产生不平衡的问题而丧失了二分查找树的优势,AVL树规定了左右孩子树的高度差超过1则为不平衡,为了维持平衡,在插入和删除子节点后,必须进行相应的旋转。还有一种著名的红黑树,红黑树放宽了平衡的要求,从而减少了操作的次数。最后还有伸展树(splay tree,好像也有叫自组织树的),它与我们前面介绍过的自组织链表中的moveToFront策略是一样的,不过用的数据结构不再是链表,而是二叉树。这几天通过亲身实现了这几种二叉树以及调试,了解了其中的很多细节,对其思想也算是有所掌握了。

因为打算后面还要实现多种树,所以先写了一个树的虚类,要实现的功能包括有insert,remove,search以及print,当然还有析构函数。

 

template<class Elem, class Key, class KEComp, class EEComp> class Tree{
	protected:
		int count;
		Tree( int c=0 ){
			count = c;
		}
		virtual ~Tree(){};
	public:
		virtual bool insert( const Elem& )=0;
		//search本来应该是const成员函数的,可是后面的splaytree在search过后
		//还要进行翻转,没办法是const的,不知道在设计上应该怎么做比较好。
		virtual bool search( const Key&, Elem& ) =0;
		virtual bool remove( const Key&, Elem& ) =0;
		virtual void print() const =0;
		int size(){	return count; }
	};

 

二分查找树的实现:

//BSTTree.h
#ifndef BSTTREE_H
#define BSTTREE_H

template<class Elem, class Key, class KEComp, class EEComp>
class BST : public Tree<Elem, Key, KEComp, EEComp>{
	protected:
		struct BinNode{
			Elem e;
			BinNode* left;
			BinNode* right;
			BinNode( Elem ee, BinNode* l=0, BinNode* r=0 ){
				e = ee; left = l; right = r;
			}
		};
		using Tree<Elem, Key, KEComp, EEComp>::count;		
		BinNode* root;
	private:
		void printHelp( BinNode* subroot, int level ) const;
		void clear( BinNode* subroot );
	
	public:
		BST(){	root = 0; }
		~BST(){
			clear( root );
		}
		
		virtual bool search( const Key& k, Elem& e );	
		virtual bool insert( const Elem& e );		
		virtual bool remove( const Key& k, Elem& e );
				
		//it's hard to print it non recursively....
		virtual void print() const{
			if( root == 0 )
				cout<<"empty tree"<<endl;
			else	printHelp( root, 0 );
			}
	};

#include "BSTTree.cpp"
#endif

 

//BSTTree.cpp
template<class Elem, class Key, class KEComp, class EEComp>
void BST<Elem, Key, KEComp, EEComp>::
	printHelp( BinNode* subroot, int level ) const{
		if( subroot == 0 ){
			return;
		}
		printHelp( subroot->left, level+1 );
		for( int i=0; i<level; i++ )
			cout<<"___";
		cout<<subroot->e<<endl;
		printHelp( subroot->right, level+1 );
	}

template<class Elem, class Key, class KEComp, class EEComp>
void BST<Elem, Key, KEComp, EEComp>::
	clear( BinNode* subroot ){
		if( subroot == 0 )
			return;
		clear( subroot->left );
		clear( subroot->right );
		delete subroot;
	}

//non recursive implementation
template<class Elem, class Key, class KEComp, class EEComp>
bool BST<Elem, Key, KEComp, EEComp>::
	search( const Key& k, Elem& e ) {
		BinNode* p = root;
		while( p != 0 ){
			if( KEComp::eq( k, p->e ) ){
				e = p->e;
				return true;
			}
			if( KEComp::lt( k, p->e ) )	
				p = p->left;
			else
				p = p->right;
			}
		return false;
	}

template<class Elem, class Key, class KEComp, class EEComp>
bool BST<Elem, Key, KEComp, EEComp>::
	insert( const Elem& e ){
		BinNode* p = root, *i=0;
		while( p!=0 ){
			i = p;
			if( EEComp::lt( e, p->e ) )
				p = p->left;
			else
				p = p->right;
		}
		p = new BinNode( e );
		if( i == 0 )
			root = p;
		else{
			if( EEComp::lt( e, i->e ) )
				i->left = p;
			else i->right = p;
			}
		count++;
		return true;
	}
	
template<class Elem, class Key, class KEComp, class EEComp>
bool BST<Elem, Key, KEComp, EEComp>::
	remove( const Key& k, Elem& e ){
		BinNode* p = root, *i=0;
		while( p!=0 ){
			if( KEComp::eq( k, p->e ) )
				break;
			i = p;
			if( KEComp::lt( k, p->e ) )
				p = p->left;
			else
				p = p->right;
		}
		if( p == 0 )
			return false;
		e = p->e;
		BinNode* removeP = p;
		if( p->right != 0 ){
			removeP = p->right;
			i = p;
			while( removeP->left != 0 ){
				i = removeP;
				removeP = removeP->left;
			}
			p->e = removeP->e;
		}
		if( i == 0 )
			root = removeP->left;
		else{
			if( i->left == removeP )
				i->left = (removeP->left==0 ? removeP->right : removeP->left);
			else
				i->right = (removeP->right==0 ? removeP->left :removeP->right);
		}
		delete removeP;
		count--;
		return true;
	}
	
	

 

AVL树比BST在插入和删除元素的时候多了一个旋转的操作。一开始的时候说什么时候只需要旋转一次,什么时候需要旋转两次的,后来想明白了,其实大致可以用下图来表示:

 

因此第二种情况下必须先把C转到B的位置使祖孙三人成一条直线,然后再做一次旋转。

AVL树的结点将比BST树的结点多一个记录高度的信息,以便在插入删除的时候确定是否需要进行旋转。因为没有记录爷结点的信息,所以是用递归实现的。

//AVLTree.h
#ifndef AVLTREE_H
#define AVLTREE_H

template<class Elem, class Key, class KEComp, class EEComp>
class AVLTree : public BST<Elem, Key, KEComp, EEComp>{
	protected:
		typedef typename BST<Elem, Key, KEComp, EEComp>::BinNode BSTNode;
		using BST<Elem, Key, KEComp, EEComp>::count;
		using BST<Elem, Key, KEComp, EEComp>::root;
		struct HeightBinNode : public BSTNode{
			int height;
			HeightBinNode( Elem ee, HeightBinNode* l=NULL, HeightBinNode* r=NULL, int h=1 ):BSTNode(ee, l, r){
				height = h;
			}
		};
	private:
		//return the height of a subtree, if the subroot is null, return 0;
		int Height( HeightBinNode* t ){
			if( t == NULL )
				return 0;
			return t->height;
		}
		Key (*getKey)(const Elem& e );
		
		//insert into the left subtree of subroot's left child
		HeightBinNode* rotateL( HeightBinNode* subroot );
		//insert into the right subtree of subroot's right child
		HeightBinNode* rotateR( HeightBinNode* subroot );
		
		//return a subroot which is modified by an inserted/removed element
		HeightBinNode* insertHelp( const Elem& e, HeightBinNode* subroot );		
		HeightBinNode* removeHelp( HeightBinNode* subroot, const Key& k, HeightBinNode*& t );
						
	public:
		AVLTree( Key (*g)(const Elem& e) ):BST<Elem, Key, KEComp, EEComp>(){
			getKey = g;
		}
			
		//since it's really hard to implement insert without recursion, 
		//I decide to realize it recursively
		bool insert( const Elem& e ){
			(HeightBinNode*)root = insertHelp( e, (HeightBinNode*)root );
			if( root == NULL )
				return false;
			count++;
			return true;
		}
		
		bool remove( const Key& k, Elem& e ){
			HeightBinNode* t=0;
			root = removeHelp( (HeightBinNode*)root, k, t );
			if( t == NULL )
				return false;
			e = t->e;
			delete t;
			count--;
			return true;
		}
	};
	
#include "AVLTree.cpp"
#endif

 

//AVLTree.cpp

template<class Elem, class Key, class KEComp, class EEComp>
typename AVLTree<Elem, Key, KEComp, EEComp>::HeightBinNode* AVLTree<Elem, Key, KEComp, EEComp>::
	rotateL( HeightBinNode* subroot ){
		HeightBinNode* alter_root = (HeightBinNode*)subroot->left;
		HeightBinNode* leftChild = (HeightBinNode* )alter_root->left, *rightChild = (HeightBinNode*) alter_root->right;
		if( Height(leftChild)-Height(rightChild) == -1 )
			alter_root = rotateR( alter_root );
		subroot->left = (HeightBinNode*)alter_root->right;
		alter_root->right = subroot;
		leftChild = (HeightBinNode*)subroot->left; rightChild = (HeightBinNode*)subroot->right;
		subroot->height = (Height(leftChild) > Height(rightChild) ? Height(leftChild):Height(rightChild))+1;
		leftChild = (HeightBinNode*)alter_root->left; rightChild = (HeightBinNode*)alter_root->right;
		alter_root->height = (Height(leftChild) > Height(rightChild) ? Height(leftChild):Height(rightChild))+1;
		return alter_root;
	}

template<class Elem, class Key, class KEComp, class EEComp>
typename AVLTree<Elem, Key, KEComp, EEComp>::HeightBinNode* AVLTree<Elem, Key, KEComp, EEComp>::
	rotateR( HeightBinNode* subroot ){
		HeightBinNode* alter_root = (HeightBinNode*)subroot->right;
		HeightBinNode* leftChild, *rightChild;
		leftChild = (HeightBinNode*) alter_root->left;
		rightChild=(HeightBinNode*)alter_root->right;
		if( Height(leftChild)-Height(rightChild) == 1 )
			alter_root = rotateL( alter_root );
		subroot->right = alter_root->left;
		alter_root->left = subroot;
		leftChild = (HeightBinNode*)subroot->left, rightChild=(HeightBinNode*)subroot->right;
		subroot->height = (Height(leftChild)>Height(rightChild) ? Height(leftChild) : Height(rightChild))+1;
		leftChild = (HeightBinNode*)alter_root->left, rightChild = (HeightBinNode*)alter_root->right;
		alter_root->height = (Height(leftChild)>Height(rightChild) ? Height(leftChild) : Height(rightChild))+1;
		return alter_root;
	}
		
template<class Elem, class Key, class KEComp, class EEComp>
typename AVLTree<Elem, Key, KEComp, EEComp>::HeightBinNode* AVLTree<Elem, Key, KEComp, EEComp>::
	insertHelp( const Elem& e, HeightBinNode* subroot ){
		if( subroot == NULL ){
			subroot = new HeightBinNode(e);
			return subroot;
		}else{
			HeightBinNode* leftChild, *rightChild;
			leftChild = (HeightBinNode*)subroot->left;
			rightChild = (HeightBinNode*)subroot->right;
			if( EEComp::lt( e, subroot->e ) ){
				leftChild = insertHelp( e, leftChild );
				subroot->left = leftChild;
				if( Height(leftChild)-Height(rightChild) == 2 )
					subroot = rotateL( subroot );
				}else{
					rightChild = insertHelp( e, rightChild );
					subroot->right = rightChild;
					if( Height(leftChild)-Height(rightChild) == -2 )
						subroot = rotateR( subroot );
					}
			subroot->height = (Height(leftChild)>Height(rightChild) ? Height(leftChild) : Height(rightChild))+1;
			return subroot;
		}
	}

template<class Elem, class Key, class KEComp, class EEComp>
typename AVLTree<Elem, Key, KEComp, EEComp>::HeightBinNode* AVLTree<Elem, Key, KEComp, EEComp>::
	removeHelp( HeightBinNode* subroot, const Key& k, HeightBinNode*& t ){
		if( subroot == NULL )
			return NULL;
		HeightBinNode* leftChild, *rightChild;
		if( KEComp::eq( k, subroot->e ) ){
			t = subroot;
			if( subroot->right == NULL ){	
				subroot = (HeightBinNode*)subroot->left;
			}else{
				BSTNode* temp = subroot->right;
				while( temp->left != NULL )	temp = temp->left;
				Elem te;
				te = subroot->e;
				subroot->e = temp->e;
				temp->e = te;				
				subroot->right = removeHelp( (HeightBinNode*)subroot->right, getKey(temp->e), t );
				leftChild = (HeightBinNode*)subroot->left; rightChild = (HeightBinNode*)subroot->right;
				subroot->height =( Height(leftChild)>Height(rightChild) ? Height(leftChild):Height(rightChild))+1;
				}
			return subroot;
		}else{
			if( KEComp::lt( k, subroot->e ) ){
				subroot->left = removeHelp( (HeightBinNode*)subroot->left, k, t );
				leftChild = (HeightBinNode*)subroot->left; rightChild = (HeightBinNode*)subroot->right;
				if( Height(leftChild)-Height(rightChild) == -2 )
					subroot = rotateR( subroot );
				}else{
					subroot->right = removeHelp( (HeightBinNode*)subroot->right, k, t );
					leftChild = (HeightBinNode*)subroot->left; rightChild = (HeightBinNode*)subroot->right;
					if( Height(leftChild)-Height(rightChild) == 2 )
						subroot = rotateL( subroot );
				}
		}
		leftChild = (HeightBinNode*)subroot->left; rightChild = (HeightBinNode*)subroot->right;
		subroot->height = (Height(leftChild)>Height(rightChild) ? Height(leftChild) : Height(rightChild))+1;
		return subroot;
	}

 

AVL树用高度来识别树的平衡程度,而红黑树则是用颜色来识别树的平衡。红黑树使用红色或者黑色来标识一个结点,一棵合法的树必须满足如下规则:

(1)树根是黑色的;

(2)空结点是黑色的;

(3)红色的父节点不能有红色的孩子结点

(4)从树根到所有叶子(空结点)的黑色结点的数目必须是相等的,从树根到叶子结点的黑色结点的数目称为树的黑高度(所有的子树也同样是一棵红黑树)。

对于插入一个结点,除了根结点外,结点必须是红色的,不然的话根到经过该结点到达空叶子结点的数目必然会比其他路径的增加一,这将违反规则4;但是如果这个时候插入结点的地方的父节点也是红色的,又会违反规则3.解决的办法是重新着父结点的颜色,将不平衡点往上推,直到最后到了根结点,根结点一定为黑;或者通过旋转降低子树的高度以同时降低子树的黑高度。具体要视叔结点的颜色而定。如下图:

删除一个结点时,我们知道,如果删除的结点左右孩子都不为空的话,我们不会直接删除该结点,而是从其孩子结点中找到大于它的最小结点(或小于它的最大结点),根据这种思想递归下去,对于物理上将被删除的结点,我们可能断定,它最多只有一个不为空的孩子,而根据结黑树的特点,如果它有一个不为空的孩子,该孩子一定为红色。总结起来,删除的结点有如下的特点:

(1)该结点没有孩子结点或只有一个红色的孩子结点

(2)如果被删除的结点是红色的,它一定是一个叶子结点。

因此,根据被删除结点的情况,删除完结点后相应的调整如下:

(1)如果被删除的结点是红色的,无须做任何调整,因为它没有影响树的黑高度。

(2)如果被删除的结点是黑色的,且其有一个孩子结点。我们知道此时该孩子结点一定为红色,因此,我们可以直接将该孩子结点染成黑色的,整体的黑高度也没有发生变化。

(3)如果被删除的结点是黑色的,其孩子结点均为空(即黑色结点)。删除该结点使经过该结点的路径的黑高度减少了一,接替该结点的位置的也将是一个黑色的新结点,这个时候,跟插入一个新的结点一样,我们要通过改变着色将冲突往上移,或者通过旋转来改变高度从而改变黑高度,因此下面的讨论就不再局限于新插入的结点。
 


 

 

 

我觉得关于红黑树这篇文章讲得很详细http://www.cppblog.com/goodwin/archive/2011/08/08/152797.html

下面是我的代码:

//RBTree.h

#ifndef RBTREE_H
#define RBTREE_H

template<class Elem, class Key, class KEComp, class EEComp>
class RBTree : public BST<Elem, Key, KEComp, EEComp>{
	protected:
		typedef enum{ BLACK,RED } Color;
		typedef typename BST<Elem, Key, KEComp, EEComp>::BinNode BSTNode;
		using BST<Elem, Key, KEComp, EEComp>::count;
		using BST<Elem, Key, KEComp, EEComp>::root;
		struct RBNode : public BSTNode{
			Color color;
			RBNode* parent;
			RBNode( Elem ee, RBNode* l=0, RBNode* r=0, RBNode* p=0, Color cc=RED ):BSTNode( ee, l, r ){
				parent = p;
				color = cc;
			}
		};
		
		void rotateL( RBNode* );
		void rotateR( RBNode* );
		void insertFixUp( RBNode* );
		void removeFixUp( RBNode* );
		/*测试用
		void printHelp( RBNode* subroot, int level ) const{
			if( subroot == 0 )
				return;
			printHelp( (RBNode*)subroot->left, level+1);
			for( int i=0; i<level; i++ )
				cout<<"___";
			if( subroot->color == BLACK )
				cout<<"("<<subroot->e<<")"<<endl;
			else
				cout<<"|"<<subroot->e<<"|"<<endl;
			printHelp( (RBNode*)subroot->right, level+1 );
		}*/
		
	public:
		RBTree(){
			//很多实现都利用了一个nilNode来做哨兵,为了利用BST的打印和删除,
			//这里没有进行这样的实现
//			nilNode = new RBNode();
//			root = nilNode;
		}
		~RBTree(){
//			delete nilNode;
		}
		bool insert( const Elem& e );
		bool remove( const Key& k, Elem& e );
		/*void print() const{
			printHelp( (RBNode*)root, 0 );
		}*/
	};

#include "RBTree.cpp"
#endif

 

//RBTree.cpp
template<class Elem, class Key, class KEComp, class EEComp>
bool RBTree<Elem, Key, KEComp, EEComp>::insert( const Elem& e ){
	if( root == 0 ){
		root = new RBNode( e );
		((RBNode*)root)->color = BLACK;
		count ++;
		return true;
	}
	RBNode *current=(RBNode*)root, *insertP;
	while( current != 0 ){
		insertP = current;
		if( EEComp::lt( e, current->e ) )
			current = (RBNode*)current->left;
		else
			current = (RBNode*)current->right;
		};
	RBNode* insertNode = new RBNode( e );
	insertNode->parent = insertP;
	if( EEComp::lt( e, insertP->e ) )
		insertP->left = insertNode;
	else
		insertP->right = insertNode;
	count ++;
	insertFixUp( insertNode );
}

template<class Elem, class Key, class KEComp, class EEComp>
void RBTree<Elem, Key, KEComp, EEComp>::
rotateL( RBNode* subroot ){
	if( subroot == 0 || subroot->left == 0 )
		return;
	RBNode* leftChild = (RBNode*)subroot->left;
	RBNode *rightChild = (RBNode*)leftChild->right;
	leftChild->parent = subroot->parent;
	if( subroot->parent == 0 )
		root = leftChild;
	else{
		if( subroot->parent->left == subroot )
			subroot->parent->left = leftChild;
		else subroot->parent->right = leftChild;
		}	
	leftChild->right = subroot;
	subroot->parent=leftChild;
	subroot->left = rightChild;
	if( rightChild != 0 )
		rightChild->parent = subroot;
}

template<class Elem, class Key, class KEComp, class EEComp>
void RBTree<Elem, Key, KEComp, EEComp>::
rotateR( RBNode* subroot ){
	if( subroot == 0 || subroot->right == 0 )
		return;
	RBNode* rightChild = (RBNode*)subroot->right;
	RBNode* leftChild = (RBNode*)rightChild->left;
	rightChild->parent = subroot->parent;
	if( subroot->parent == 0 )
		root = rightChild;
	else{
		if( subroot->parent->left == subroot )
			subroot->parent->left = rightChild;
		else
			subroot->parent->right = rightChild;
		}
	rightChild->left = subroot;
	subroot->parent = rightChild;
	subroot->right = leftChild;
	if( leftChild != 0 )
		leftChild->parent = subroot;
}

template<class Elem, class Key, class KEComp, class EEComp>
void RBTree<Elem, Key, KEComp, EEComp>::	
insertFixUp( RBNode* current ){
	while( current->parent != 0 && current->parent->color == RED ){
		RBNode* uncle;
		if( current->parent == current->parent->parent->left ){
			uncle = (RBNode*)current->parent->parent->right;
			if( uncle !=0 && uncle->color == RED ){
				current->parent->color = BLACK;
				uncle->color = BLACK;
				current = current->parent->parent;
				current->color = RED;
			}else{
				if( current == current->parent->right ){
					current = current->parent;
					rotateR( current );
				}
				current->parent->color = BLACK;
				current->parent->parent->color = RED;
				rotateL( current->parent->parent );
			}
		}else{
			uncle = (RBNode*)current->parent->parent->left;
			if( uncle != 0 && uncle->color == RED ){
				current->parent->color = BLACK;
				uncle->color = BLACK;
				current = current->parent->parent;
				current->color = RED;
			}else{
				if( current == current->parent->left ){
					current = current->parent;
					rotateL( current );
				}
				current->parent->color = BLACK;
				current->parent->parent->color = RED;
				rotateR( current->parent->parent );
			}
		}
	}
	((RBNode*)root)->color = BLACK;
}

template<class Elem, class Key, class KEComp, class EEComp>
bool RBTree<Elem, Key, KEComp, EEComp>::
remove( const Key& k, Elem& e ){
	RBNode* index=(RBNode*)root, *removeNode=0;
	//get the node to be removed
	while( index != 0 ){
		if( KEComp::eq( k, index->e ) ){
			e = index->e;
			if( index->right == 0 ){
				removeNode = index;
				break;
			}else{
				BSTNode* temp = index->right;
				while( temp->left != 0 )
					temp = temp->left;
				removeNode = (RBNode*)temp;
				index->e = temp->e;
				break;
			}
		}
		if( KEComp::lt( k, index->e ) )
			index = (RBNode*)index->left;
		else
			index = (RBNode*)index->right;
		}
	if( removeNode == 0 )
		return false;
	
	//没有使用哨兵的结果还是挺严重的,代码写得很不简洁。
	if( removeNode->color == RED ){		//red child is a leaf
		if( removeNode->parent->left == removeNode )
			removeNode->parent->left = 0;
		else
			removeNode->parent->right = 0;
		}else{
			if( removeNode == root ){
				root = removeNode->left;
				if( root != 0 )
					((RBNode*)root)->color = BLACK;
				}
			else{
				RBNode* child=0;
				if( removeNode->left != 0 )
					child = (RBNode*)removeNode->left;
				else
					child = (RBNode*)removeNode->right;
				RBNode* temp=0;
				if ( child == 0 ){
					temp = new RBNode(e);
					child = temp;
					child->color = BLACK;
					child->parent = removeNode->parent;
				}
				bool left;
				if( removeNode == removeNode->parent->left ){
					left = true;
					removeNode->parent->left = child;
				}
				else{
					removeNode->parent->right = child;
					left = false;
				}
				removeFixUp( child );
				if( temp != 0 ){
					if( left )
						temp->parent->left = 0;
					else
						temp->parent->right = 0;
					delete temp;
				}
			}
		}
	delete removeNode;
	count --;
	return true;
}

template<class Elem, class Key, class KEComp, class EEComp>
void RBTree<Elem, Key, KEComp, EEComp>::
removeFixUp( RBNode* current ){
	while( current != root && current->color == BLACK ){
		RBNode* uncle, *leftChild, *rightChild;
		if( current == current->parent->left ){		//left child
			uncle = (RBNode*)current->parent->right;
			//uncle is impossible to be null
			if( uncle->color == RED ){
				current->parent->color = RED;
				uncle->color = BLACK;
				rotateL( current->parent );
				uncle = (RBNode*)current->parent->right;
			}
			leftChild = (RBNode*)uncle->left;
			rightChild =(RBNode*)uncle->right;
			if( (leftChild==0||leftChild->color==BLACK) && 
				(rightChild==0 || rightChild->color==BLACK) ){
				uncle->color = RED;
				current = current->parent;
			}else{
				if( leftChild!=0 && leftChild->color == RED ){
					leftChild->color = BLACK;
					uncle->color = RED;
					rotateL( uncle );
					uncle = (RBNode*)current->parent->right;
				}
				uncle->color = current->parent->color;
				current->parent->color = BLACK;
				((RBNode*)uncle->right)->color = BLACK;
				rotateR( current->parent );
				current = (RBNode*)root;
			}
		}else{	//right child, which is symmetric with left child
			uncle = (RBNode*)current->parent->left;
			if( uncle->color == RED ){
				current->parent->color = RED;
				uncle->color = BLACK;
				rotateL( current->parent );
				uncle = (RBNode*)current->parent->left;
			}
			leftChild = (RBNode*)uncle->left;
			rightChild = (RBNode*)uncle->right;
			if( (leftChild==0 || leftChild->color==BLACK) &&
				(rightChild==0 || rightChild->color==BLACK) ){
					uncle->color = RED;
					current = current->parent;
				}else{
					if( rightChild->color == RED ){
						uncle->color = RED;
						rightChild->color = BLACK;
						rotateR( uncle );
						uncle = (RBNode*)current->parent->left;
					}
					uncle->color = current->parent->color;
					current->parent->color = BLACK;
					((RBNode*)uncle->left)->color = BLACK;
					rotateL( current->parent );
					current = (RBNode*)root;
				}
			}
		}
		current->color = BLACK;
	}

 最后一种是splay树。Splay树是一种自组织树,跟MoveToFront的自组织链表一样,刚被搜索到的元素被转到树根,转的方法如下:

 

代码如下:

//BSTTree.h
#ifndef BSTTREE_H
#define BSTTREE_H

template<class Elem, class Key, class KEComp, class EEComp>
class BST : public Tree<Elem, Key, KEComp, EEComp>{
	protected:
		struct BinNode{
			Elem e;
			BinNode* left;
			BinNode* right;
			BinNode( Elem ee, BinNode* l=0, BinNode* r=0 ){
				e = ee; left = l; right = r;
			}
		};
		using Tree<Elem, Key, KEComp, EEComp>::count;		
		BinNode* root;
	private:
		void printHelp( BinNode* subroot, int level ) const;
		void clear( BinNode* subroot );
	
	public:
		BST(){	root = 0; }
		~BST(){
			clear( root );
		}
		
		virtual bool search( const Key& k, Elem& e );	
		virtual bool insert( const Elem& e );		
		virtual bool remove( const Key& k, Elem& e );
				
		//it's hard to print it non recursively....
		virtual void print() const{
			if( root == 0 )
				cout<<"empty tree"<<endl;
			else	printHelp( root, 0 );
			}
	};

#include "BSTTree.cpp"
#endif

 

//SplayTree.cpp

template<class Elem, class Key, class KEComp, class EEComp>
void SplayTree<Elem, Key, KEComp, EEComp>::
rotateL( SPNode* subroot ){
	if( subroot == 0 || subroot->left == 0 )
		return;
	SPNode* leftChild = (SPNode*)subroot->left, *rightChild = (SPNode*)leftChild->right;
	if( subroot == root )
		root = leftChild;
	else{
		if( subroot == subroot->parent->left )
			subroot->parent->left = leftChild;
		else
			subroot->parent->right = leftChild;
		}
	leftChild->parent = subroot->parent;
	leftChild->right = subroot;
	subroot->parent = leftChild;
	subroot->left = rightChild;
	if( rightChild != 0 )
		rightChild->parent = subroot;
}

template<class Elem, class Key, class KEComp, class EEComp>
void SplayTree<Elem, Key, KEComp, EEComp>::
rotateR( SPNode* subroot ){
	if( subroot == 0 || subroot->right == 0 )
		return;
	SPNode* rightChild = (SPNode*)subroot->right, *leftChild =(SPNode*)rightChild->left;
	if( subroot == root )
		root = rightChild;
	else{
		if( subroot == subroot->parent->left )
			subroot->parent->left = rightChild;
		else
			subroot->parent->right = rightChild;
		}
	rightChild->parent = subroot->parent;
	rightChild->left = subroot;
	subroot->right = leftChild;
	subroot->parent = rightChild;
	if( leftChild != 0 )
		leftChild->parent = subroot;
}

template<class Elem, class Key, class KEComp, class EEComp>
void SplayTree<Elem, Key, KEComp, EEComp>::
	splay( SPNode* from, SPNode* to ){	//rotate from under to
		if( from == 0 )
			return;
		while( from->parent != to ){
			if( from->parent->parent == to ){
				if( from == from->parent->left )
					rotateL( from->parent );
				else	rotateR( from->parent );
				}
			else{
				SPNode* p=from->parent, *g=p->parent;
				if( from == (SPNode*)p->left ){
					
					if( p == (SPNode*)g->left ){
						rotateL( g );
						rotateL( p );
					}else{
						rotateL( p );
						rotateR( g );
					}
				}else{
					if( p == (SPNode*)g->right ){
						rotateR( g );
						rotateR( p );
					}else{
						rotateR( p );
						rotateL( g );
					}
				}
			}
		}
	}

template<class Elem, class Key, class KEComp, class EEComp>
bool SplayTree<Elem, Key, KEComp, EEComp>::
	insert( const Elem& e ){
		if( root == 0 ){
			root = new SPNode( e );
			((SPNode*) root)->parent = 0;
			count ++;
			return true;
		}
		SPNode* index=(SPNode*)root, *insertP;
		while( index != 0 ){
			insertP = index;
			if( EEComp::lt( e, index->e ) )
				index = (SPNode*)index->left;
			else
				index = (SPNode*)index->right;
			}
		index = new SPNode( e );
		index->parent = insertP;
		if( EEComp::lt( e, insertP->e ) )
			insertP->left = index;
		else
			insertP->right = index;
		splay( index, 0 );
		count++;
		return true;
	}

template<class Elem, class Key, class KEComp, class EEComp>
bool SplayTree<Elem, Key, KEComp, EEComp>::
	remove( const Key& k, Elem& e ){
		SPNode* removeP = (SPNode*)root;
		SPNode* splayP;
		while( removeP != 0 ){
			if( KEComp::eq( k, removeP->e ) ){
				e = removeP->e;
				splayP = removeP->parent;
				if( removeP->right == 0 && splayP !=0 ){
					if( removeP == splayP->left )
						splayP->left = removeP->left;
					else
						splayP->right = removeP->left;
					if( removeP->left != 0 )
						((SPNode*)removeP->left)->parent = splayP;
					}else{
					SPNode* temp = (SPNode*)removeP->right;
					while( temp->left != 0 )	temp = (SPNode*)temp->left;
					temp->parent->left = temp->right;
					if( temp->right != 0 )
						((SPNode*)temp->right)->parent = temp->parent;
					removeP->e = temp->e;
					removeP = temp;
				}
			delete removeP;
			splay( splayP, 0 );
			count--;
			return true;
		}else{
			if( KEComp::lt( k, removeP->e ) )
				removeP = (SPNode*)removeP->left;
			else
				removeP = (SPNode*)removeP->right;
			}
		}
		return false;
	}

template<class Elem, class Key, class KEComp, class EEComp>
bool SplayTree<Elem, Key, KEComp, EEComp>::
	search( const Key& k, Elem& e ) const{
		SPNode* searchP = (SPNode*)root;
		while( searchP != 0 ){
			if( KEComp::eq( k, searchP->e ) ){
				e = searchP->e;
				splay( searchP );
				return true;
			}else{
				if( KEComp::lt( k, searchP->e ) )
					searchP = searchP->left;
				else
					searchP = searchP->right;
				}
			}
		return false;
	}

 

基本就是这些了。接下来再实现一下其他类型的树,呵呵。

  • 大小: 27 KB
  • 大小: 83.6 KB
  • 大小: 25.3 KB
  • 大小: 42.9 KB
  • 大小: 42.7 KB
  • 大小: 21.4 KB
  • 大小: 54.9 KB
分享到:
评论

相关推荐

    SplayTree详细解释

    除了SplayTree之外,还有多种平衡二叉搜索树,比如AVL树、Treap、跳跃表(SkipList)和红黑树(RBTree)等。 - **AVL Tree**:通过限制每个节点的左右子树高度差不超过1来保持平衡。 - **Treap**:结合了二叉搜索树和堆...

    :link:常用的数据结构和算法

    6. **二叉搜索树(Binary Search Tree, BST)和红黑树(Red-Black Tree, RBTree)**: 二叉搜索树是一种自平衡的搜索树,而红黑树是二叉搜索树的一种变体,它通过颜色属性(红色或黑色)确保了插入、删除和查找操作的...

    动态搜索树总结

    动态搜索树是一种在数据结构领域中用于高效存储和检索数据的树形结构,常见的动态搜索树包括BSTree(二叉搜索树)、RBTree(红黑树)、BBSTree(通常指的是avl树,一种自平衡二叉搜索树)以及BTree和B+Tree。...

    ### 制造业上市公司高质量发展研究报告(2023年)

    内容概要:报告由中国信息通信研究院发布,旨在评估制造业上市公司高质量发展,强调制造业高质量发展的重要性,并构建了涵盖创新力、竞争力、影响力、贡献力四大维度的评价体系。通过对3500余家制造业上市公司2022年年报数据的综合评估,评选出百强企业。研究显示,百强企业专注主业,半数以上成长为制造业单项冠军;民营企业在盈利效率、创新发展方面表现优异;东部地区引领发展,装备制造业领先,新能源产业呈现爆发性增长。百强企业在科技创新、质效提升、持续增长、稳定就业等方面发挥重要作用,但也存在品牌建设和创新水平差距、领军企业竞争力提升空间、高端领域龙头企业培育不足等问题。 适用人群:制造业企业管理者、政策制定者、投资者及相关研究人员。 使用场景及目标:①帮助企业管理者了解行业发展趋势,提升企业竞争力;②为政策制定者提供决策参考,推动制造业高质量发展;③为投资者提供投资参考,识别优质企业;④为研究人员提供详实数据,助力学术研究。 其他说明:报告建议从重突破促升级、重创新补短板、重质量树品牌三个方面进一步推进制造业企业高质量发展,以加快建设具有全球竞争力的一流企业。

    异步电机无感矢量控制仿真:关键技术和代码实现技巧

    内容概要:本文详细介绍了异步电机无感矢量控制仿真的关键技术与常见问题解决方案。首先讨论了坐标变换(Clarke和Park变换)的基础操作及其注意事项,强调了正确选择系数的重要性。接下来深入探讨了滑模观测器的设计与优化方法,包括使用查表法替代三角函数计算以提高效率,以及加入低通滤波器减少高频抖振。此外,文章还涉及了速度估算的方法,如频域法和改进型滑模观测器的应用,并提供了具体的Python和Matlab代码片段。最后,针对电流环控制提出了前馈补偿机制,确保在突加负载情况下仍能保持良好的电流跟踪效果。文中多次提到调参技巧,特别是对于PI参数的选择给出了实用建议。 适合人群:从事电机控制系统研究与开发的技术人员,尤其是对异步电机无感矢量控制感兴趣的工程师。 使用场景及目标:适用于希望深入了解并掌握异步电机无感矢量控制仿真技术的研究人员和技术开发者。主要目标是在没有编码器的情况下实现对电机转速和扭矩的精确控制,同时提供详细的代码实现指导和调试经验。 其他说明:文章不仅提供了理论知识,还包括大量实际操作中的经验和教训,帮助读者避免常见的陷阱,快速搭建起有效的仿真环境。

    (源码)基于Arduino的火箭动力学参数监测项目.zip

    # 基于Arduino的火箭动力学参数监测项目 ## 项目简介 这是一个基于Arduino平台的火箭动力学参数监测项目,旨在通过Adafruit BMP280压力传感器和Adafruit LIS3DH加速度传感器收集火箭飞行过程中的环境数据和运动数据。项目结合了Adafruit的BMP280库和LIS3DH库,实现对传感器数据的读取、处理及初步分析。 ## 项目的主要特性和功能 1. 环境数据监测通过BMP280压力传感器,实时监测并记录火箭周围的气压、温度和海拔高度变化。 2. 运动数据监测借助LIS3DH加速度传感器,获取火箭在飞行过程中的加速度、速度及方向变化数据。 3. 数据处理与传输Arduino负责收集和初步处理这些数据,然后通过串行通信或其他方式将数据发送到地面站或飞行控制软件。 4. 安全与警报基于收集的数据,项目可设置警报阈值,当超过预设的安全限制时,触发警报或采取相应的安全措施。 ## 安装使用步骤

    (源码)基于Arduino的EPSleepy智能家居控制系统.zip

    # 基于Arduino的EPSleepy智能家居控制系统 ## 一、项目简介 EPSleepy是一个基于Arduino的智能家居控制系统原型。该项目旨在通过Arduino控制ESP32 WiFi和蓝牙板,结合MP3模块、shiftregister和按钮等硬件,实现智能家居的自动化控制。 ## 二、项目的主要特性和功能 1. 自动化控制通过Arduino代码控制ESP32板,实现家居设备的自动化控制。 2. 多种硬件支持支持MP3模块、shiftregister和按钮等硬件,实现音频播放、灯光控制、SD驱动等功能。 3. 模块化设计代码采用模块化设计,方便测试每个部分的功能,方便维护和调试。 4. 图形化界面可通过按钮和LED等硬件进行图形化操作和控制。 ## 三、安装使用步骤 1. 下载并解压项目源码文件。 2. 打开Arduino IDE,导入项目代码。 3. 连接硬件,包括ESP32板、MP3模块、shiftregister和按钮等。

    Delphi 12.3控件之PowerPDF for Delphi11 FullSource.zip

    Delphi 12.3控件之PowerPDF for Delphi11 FullSource.zip

    电动工具领域中微CMS32M5533 800W角磨机方案的硬件设计与反电动势检测算法详解

    内容概要:本文深入探讨了中微CMS32M5533在800W角磨机方案中的应用,涵盖硬件设计和软件实现的关键技术。硬件方面,介绍了三相桥驱动电路、MOSFET选择、电流检测电阻、PCB布局等细节;软件方面,重点讲解了反电动势检测算法、ADC采样时机、PWM配置以及换相时机的动态补偿。此外,还提供了调试技巧和成本控制方法。 适合人群:从事电动工具开发的技术人员,尤其是对电机控制有一定经验的研发人员。 使用场景及目标:适用于希望深入了解电动工具控制系统的设计和优化,特别是希望通过反电动势检测减少霍尔传感器使用的开发者。目标是提高系统的可靠性和性能,同时降低成本。 其他说明:文中提供的代码片段和硬件设计细节有助于实际项目的开发和调试。建议读者结合提供的GitHub资源进行实践,并关注硬件选型和PCB布局的注意事项。

    2004-2023年 上市公司CEO绿色经历

    CEO的绿色经历是指该首席执行官(CEO)在其个人职业发展过程中,所积累的与环境保护、可持续发展、绿色经济等相关的教育背景、工作经验或社会活动经验。 涵盖了教育背景、工作经验、社会活动与个人价值观等多个方面。这些经历不仅塑造了CEO对环境保护和可持续发展的认知和态度,还可能影响他们在企业决策中优先考虑环保因素的程度,从而对企业的长期发展和环境保护产生重要影响。 根据现有研究(姜付秀和黄继承,2013;许年行和李哲,2016),从高管个人简历数据中查找CEO以前是否接受过“绿色”相关教育或从事过“绿色”相关工作,若企业CEO具有绿色经历,Green取值1,否则,取值0。 数据 Stkcd、年份、D0801c、Green、股票简称、行业名称、行业代码、制造业取两位代码,其他行业用大类、当年ST或PT为1,否则为0、样本区间内ST或PT为1,否则为0、金融业为1,否则为0、制造业为1,否则为0、沪深A股为1,否则为0、第一种重污染行业为1,否则为0、第二种重污染行业为1,否则为0、第三种重污染行业为1,否则为0、产权性质,国企为1,否则为0、所属省份代码、所属城市代码、所在省份、所在地级市

    电动汽车18650电池组蛇形液冷系统的COMSOL多物理场仿真与优化

    内容概要:本文详细介绍了利用COMSOL Multiphysics对18650电池组进行蛇形液冷系统仿真的全过程。首先探讨了快充场景下电池过热的风险及其对电动车安全性和寿命的影响。接着,通过集总电池模型简化电化学反应,重点分析了电池产热方程和温度对产热的影响。随后,深入讨论了蛇形流道几何参数优化,如流道宽度与压降之间的非线性关系,以及流固交界面处理方法。此外,还涉及了多物理场耦合求解技巧,包括流场与传热模块的设置,以及后处理阶段的数据提取和可视化。最终得出优化设计方案,显著降低了电池组的最高温度和温度不均性。 适合人群:从事电动汽车电池管理系统设计的研究人员和技术工程师,尤其是熟悉COMSOL仿真工具的专业人士。 使用场景及目标:适用于需要评估和优化电动汽车电池组热管理系统的场合,旨在提高电池组的安全性和使用寿命,同时减少能量损耗。 其他说明:文中提供了大量具体的代码片段和参数设置建议,有助于读者快速上手并应用于实际工程项目中。

    通信领域CCSDS LDPC译码器设计:基于修正最小和算法的C语言与Vivado实现

    内容概要:本文详细介绍了CCSDS LDPC译码器的设计与实现,主要采用了修正最小和译码算法。该算法通过对传统最小和算法的改进,引入缩放因子α,提高了译码性能。文中具体讨论了(8176,7154)和(1280,1024)两种码组的应用场景及其优劣,并展示了如何通过C语言和Vivado进行仿真和硬件实现。此外,文章还探讨了硬件实现中的关键技术,如定点化处理、校验矩阵的压缩存储、动态阈值机制以及硬件流水线设计等。 适合人群:从事通信系统开发的研究人员和技术人员,尤其是对LDPC编码和译码感兴趣的工程师。 使用场景及目标:①帮助研究人员理解和实现CCSDS LDPC译码器;②为实际工程项目提供高效的译码解决方案;③提高译码性能,减少误码率,提升通信系统的可靠性和效率。 其他说明:文章不仅提供了理论分析,还包括了大量的代码示例和实践经验分享,有助于读者全面掌握CCSDS LDPC译码器的设计与实现。

    (源码)基于Arduino的超声波距离测量系统.zip

    # 基于Arduino的超声波距离测量系统 ## 项目简介 本项目是一个基于Arduino平台的超声波距离测量系统。系统包含四个超声波传感器(SPS)模块,用于测量与前方不同方向物体的距离,并通过蜂鸣器(Buzz)模块根据距离范围给出不同的反应。 ## 项目的主要特性和功能 1. 超声波传感器(SPS)模块每个模块包括一个超声波传感器和一个蜂鸣器。传感器用于发送超声波并接收回波,通过计算超声波旅行时间来确定与物体的距离。 2. 蜂鸣器(Buzz)模块根据超声波传感器测量的距离,蜂鸣器会给出不同的反应,如延时发声。 3. 主控制器(Arduino)负责控制和管理所有传感器和蜂鸣器模块,通过串行通信接收和发送数据。 4. 任务管理通过主控制器(Arduino)的 loop() 函数持续执行传感器任务(Task),包括测距、数据处理和蜂鸣器反应。 ## 安装使用步骤 1. 硬件连接

    主角跑步动作素材图包含6张图片

    主角跑步动作素材图包含6张图片

    2003-2023年 企业数字化转型测算结果

    企业数字化转型是指企业或组织将传统业务转化为数字化业务,利用人工智能、大数据、云计算、区块链、5G等数字技术提升业务效率和质量的过程。 当无形资产明细项包含“软件”“网络”“客户端”“管理系统”“智能平台”等与数字化转型技术相关的关键词以及与此相关的专利时,将该明细项目界定为“数字化技术无形资产”,再对同一公司同年度多项数字化技术无形资产进行加总,计算其占本年度无形资产的比例,即为企业数字化转型程度的代理变量。 本数据包含:原始数据、参考文献、代码do文件、最终结果。 参考文献:张永珅,李小波,邢铭强-企业数字化转型与审计定价[J].审计研究,2021(03):62-71. 数据 证券代码、证券简称、统计截止日期、报表类型、无形资产净额、资产总计、年份、期末余额(元)、数字化转型。

    h5py-3.1.0-cp36-cp36m-win_amd64.whl

    该资源为h5py-3.1.0-cp36-cp36m-win_amd64.whl,欢迎下载使用哦!

    QRBayes-LSTM用于Excel数据的多/单变量时序预测及其应用

    内容概要:本文介绍了一种基于QRBayes-LSTM的多/单变量时序预测方法,适用于不确定性强的场景如股票预测和电力负荷预测。该方法结合了分位数回归和贝叶斯优化,不仅能提供未来的趋势预测,还能给出预测值的置信区间。文中详细解释了数据准备、模型结构、损失函数设计、训练配置以及预测结果的可视化和评估指标。此外,还提供了变量重要性分析的方法,帮助理解哪些特征对预测结果的影响最大。 适合人群:从事数据分析、机器学习研究的专业人士,尤其是关注时序预测和不确定性量化的人群。 使用场景及目标:① 对于需要进行时序预测并希望获得置信区间的用户;② 关注模型性能评估和变量重要性的研究人员;③ 寻求提高预测精度和可靠性的从业者。 其他说明:本文提供的代码可以直接应用于Excel格式的数据,用户只需将数据导入即可运行。需要注意的是,为了获得最佳效果,应该确保数据格式正确并且符合特定的要求。

    ADAS系统核心技术解析:ACC、FCW、AEB、LKA的设计与实现

    内容概要:本文详细介绍了ADAS(高级驾驶辅助系统)中四个主要功能模块的设计与实现,分别是自适应巡航控制系统(ACC)、前向碰撞预警系统(FCW)、自动紧急制动系统(AEB)和车道保持辅助系统(LKA)。文章不仅展示了各个系统的具体算法实现,如ACC中的PID控制、FCW中的TTC计算、AEB中的状态机设计和LKA中的PD控制器,还分享了许多实际开发中的经验和挑战,如参数调校、传感器融合、时间同步等问题。此外,文中还提到了一些有趣的细节,如在暴雨天气下LKA的表现优化,以及AEB系统在测试过程中遇到的各种corner case。 适合人群:汽车电子工程师、自动驾驶研究人员、嵌入式软件开发者。 使用场景及目标:帮助读者深入了解ADAS系统的工作原理和技术细节,掌握关键算法的实现方法,提高在实际项目中的开发和调试能力。 其他说明:文章通过生动的语言和具体的代码示例,使复杂的理论变得通俗易懂,有助于初学者快速入门并深入理解ADAS系统的开发流程。

    【高端制造业】2023年中国上市公司行业与区域分布分析:机械制造、电子、电力设备领头沿海地区优势明显

    内容概要:文章主要阐述了2023年中国高端制造业上市公司的发展概况,包括行业与区域两个维度的分布详情。从行业上看,高端制造业上市公司超过2400家,其中机械制造以628家的数量位居首位,电子(352家)和电力制造(336家)紧随其后,而像航空航天国防等也有一定的占比。从区域分布来看,广东、江苏、浙江三省处于领先地位,分别有410家、342家和199家,这表明东南沿海地区对于高端制造业的发展具有显著优势。数据来源于中国上市公司协会以及Wind。 适合人群:对中国经济结构、产业发展趋势感兴趣的读者,尤其是关注高端制造业发展的投资者、政策制定者及研究人员。 使用场景及目标:①帮助投资者了解中国高端制造业上市公司的行业布局,为投资决策提供参考依据;②为政策制定者提供数据支持,助力优化产业布局和发展规划;③供研究人员分析中国高端制造业的现状与未来发展趋势。 阅读建议:本文提供了丰富的数据和图表,读者应重点关注各行业的具体数据及其背后反映出的产业特点,同时结合区域分布情况,深入理解中国高端制造业的发展格局。

    (源码)基于Python的机器学习算法实践.zip

    # 基于Python的机器学习算法实践 ## 项目简介 本项目旨在通过实践常用机器学习算法,提高数据挖掘和推荐系统的准确性,解决信息过载问题。应用场景包括电商、新闻、视频等网站,帮助用户更高效地获取所需信息。 ## 项目的主要特性和功能 数据挖掘实现多种数据挖掘算法,帮助用户从大量数据中提取有价值的信息。 机器学习算法包括常用的分类、回归、聚类等算法,提供详细的实现和示例程序。 推荐系统通过机器学习算法提高推荐系统的准确性,优化用户体验。 ## 安装使用步骤 1. 下载源码用户已下载本项目的源码文件。 2. 安装依赖 bash pip install r requirements.txt 3. 运行示例程序 bash python main.py 4. 自定义数据根据需要替换数据文件,重新运行程序以应用新的数据。

Global site tag (gtag.js) - Google Analytics