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

数据结构 -- 二叉树(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。...

    【KUKA 机器人资料】:激光跟踪焊接机器人系统技术方案.pdf

    KUKA机器人相关资料

    基于Matlab的模拟退火算法在旅行商问题(TSP)优化中的应用及其实现

    内容概要:本文详细介绍了利用Matlab实现模拟退火算法来优化旅行商问题(TSP)。首先阐述了TSP的基本概念及其在路径规划、物流配送等领域的重要性和挑战。接着深入讲解了模拟退火算法的工作原理,包括高温状态下随机探索、逐步降温过程中选择较优解或以一定概率接受较差解的过程。随后展示了具体的Matlab代码实现步骤,涵盖城市坐标的定义、路径长度的计算方法、模拟退火主循环的设计等方面。并通过多个实例演示了不同参数配置下的优化效果,强调了参数调优的重要性。最后讨论了该算法的实际应用场景,如物流配送路线优化,并提供了实用技巧和注意事项。 适合人群:对路径规划、物流配送优化感兴趣的科研人员、工程师及高校学生。 使用场景及目标:适用于需要解决复杂路径规划问题的场合,特别是涉及多个节点间最优路径选择的情况。通过本算法可以有效地减少路径长度,提高配送效率,降低成本。 其他说明:文中不仅给出了完整的Matlab代码,还包括了一些优化建议和技术细节,帮助读者更好地理解和应用这一算法。此外,还提到了一些常见的陷阱和解决方案,有助于初学者避开常见错误。

    基于STM32的永磁同步电机Simulink代码生成与57次谐波抑制的霍尔FOC控制

    内容概要:本文详细介绍了如何利用Simulink进行自动代码生成,在STM32平台上实现带57次谐波抑制功能的霍尔场定向控制(FOC)。首先,文章讲解了所需的软件环境准备,包括MATLAB/Simulink及其硬件支持包的安装。接着,阐述了构建永磁同步电机(PMSM)霍尔FOC控制模型的具体步骤,涵盖电机模型、坐标变换模块(如Clark和Park变换)、PI调节器、SVPWM模块以及用于抑制特定谐波的陷波器的设计。随后,描述了硬件目标配置、代码生成过程中的注意事项,以及生成后的C代码结构。此外,还讨论了霍尔传感器的位置估算、谐波补偿器的实现细节、ADC配置技巧、PWM死区时间和换相逻辑的优化。最后,分享了一些实用的工程集成经验,并推荐了几篇有助于深入了解相关技术和优化控制效果的研究论文。 适合人群:从事电机控制系统开发的技术人员,尤其是那些希望掌握基于Simulink的自动代码生成技术,以提高开发效率和控制精度的专业人士。 使用场景及目标:适用于需要精确控制永磁同步电机的应用场合,特别是在面对高次谐波干扰导致的电流波形失真问题时。通过采用文中提供的解决方案,可以显著改善系统的稳定性和性能,降低噪声水平,提升用户体验。 其他说明:文中不仅提供了详细的理论解释和技术指导,还包括了许多实践经验教训,如霍尔传感器处理、谐波抑制策略的选择、代码生成配置等方面的实际案例。这对于初学者来说是非常宝贵的参考资料。

    基于S7-200 PLC和组态王的机械手搬运控制系统设计与调试

    内容概要:本文详细介绍了基于西门子S7-200 PLC和组态王的机械手搬运控制系统的实现方案。首先,文章展示了梯形图程序的关键逻辑,如急停连锁保护、水平移动互锁以及定时器的应用。接着,详细解释了IO分配的具体配置,包括数字输入、数字输出和模拟量接口的功能划分。此外,还讨论了接线图的设计注意事项,强调了电磁阀供电和继电器隔离的重要性。组态王的画面设计部分涵盖了三层画面结构(总览页、参数页、调试页)及其动画脚本的编写。最后,分享了调试过程中遇到的问题及解决方案,如传感器抖动、输出互锁设计等。 适合人群:从事自动化控制领域的工程师和技术人员,尤其是对PLC编程和组态软件有一定基础的读者。 使用场景及目标:适用于自动化生产线中机械手搬运控制系统的开发与调试。目标是帮助读者掌握从硬件接线到软件逻辑的完整实现过程,提高系统的稳定性和可靠性。 其他说明:文中提供了大量实践经验,包括常见的错误和解决方案,有助于读者在实际工作中少走弯路。

    西门子1200PLC污水处理项目:PLC程序、通讯配置与HMI设计详解

    内容概要:本文详细介绍了基于西门子1200PLC的污水处理项目,涵盖了PLC程序结构、通信配置、HMI设计以及CAD原理图等多个方面。PLC程序采用梯形图和SCL语言相结合的方式,实现了复杂的控制逻辑,如水位控制、曝气量模糊控制等。通讯配置采用了Modbus TCP和Profinet双协议,确保了设备间高效稳定的通信。HMI设计则注重用户体验,提供了详细的报警记录和趋势图展示。此外,CAD图纸详尽标注了设备位号,便于后期维护。操作说明书中包含了应急操作流程和定期维护建议,确保系统的长期稳定运行。 适合人群:从事工业自动化领域的工程师和技术人员,尤其是对PLC编程、HMI设计和通信配置感兴趣的从业者。 使用场景及目标:适用于污水处理厂及其他类似工业控制系统的设计、实施和维护。目标是帮助工程师掌握完整的项目开发流程,提高系统的可靠性和效率。 其他说明:文中提供的具体代码片段和设计思路对于理解和解决实际问题非常有价值,建议读者结合实际项目进行深入学习和实践。

    5电平三相MMC的VSG控制与MATLAB-Simulink仿真:调频调压效果验证

    内容概要:本文详细介绍了基于5电平三相模块化多电平变流器(MMC)的虚拟同步发电机(VSG)控制系统的构建与仿真。首先,文章描述了MMC的基本结构和参数设置,包括子模块电容电压均衡策略和载波移相策略。接着,深入探讨了VSG控制算法的设计,特别是有功-频率和无功-电压下垂控制的具体实现方法。文中还展示了通过MATLAB-Simulink进行仿真的具体步骤,包括设置理想的直流电源和可编程三相源来模拟电网扰动。仿真结果显示,VSG控制系统能够在面对频率和电压扰动时迅速恢复稳定,表现出良好的调频调压性能。 适合人群:从事电力电子、电力系统自动化及相关领域的研究人员和技术人员。 使用场景及目标:适用于研究和开发新型电力电子设备,特别是在新能源接入电网时提高系统的稳定性。目标是通过仿真验证VSG控制的有效性,为实际应用提供理论支持和技术指导。 其他说明:文章提供了详细的代码片段和仿真配置,帮助读者更好地理解和重现实验结果。此外,还提到了一些常见的调试技巧和注意事项,如选择合适的仿真步长和参数配对调整。

    工业自动化中基于PLC1200的SCL与梯形图混编立体库及码垛系统的通信与控制

    内容概要:本文详细介绍了在一个复杂的工业自动化项目中,如何利用西门子S7-1200 PLC为核心,结合基恩士视觉相机、ABB机器人以及G120变频器等多种设备,构建了一个高效的立体库码垛系统。文中不仅探讨了不同设备之间的通信协议(如Modbus TCP和Profinet),还展示了SCL和梯形图混合编程的具体应用场景和技术细节。例如,通过SCL进行视觉坐标解析、机器人通信心跳维护等功能的实现,而梯形图则用于处理简单的状态切换和安全回路。此外,作者分享了许多实际调试过程中遇到的问题及其解决方案,强调了良好的注释习惯对于提高代码可维护性的关键作用。 适用人群:从事工业自动化领域的工程师和技术人员,尤其是对PLC编程、机器人控制及多种通信协议感兴趣的从业者。 使用场景及目标:适用于需要整合多种工业设备并确保它们能够稳定协作的工作环境。主要目标是在保证系统高精度的同时降低故障率,从而提升生产效率。 其他说明:文中提到的一些具体技术和方法可以作为类似项目的参考指南,帮助开发者更好地理解和应对复杂的工业控制系统挑战。

    【KUKA 机器人资料】:KUKA机器人_Interbus_输入输出端口配置说明书.pdf

    KUKA机器人相关资料

    java脱敏工具类,敏感数据脱敏

    java脱敏工具类

    基于自抗扰控制的表贴式永磁同步电机双环控制系统设计与实现

    内容概要:本文详细介绍了基于自抗扰控制(ADRC)的表贴式永磁同步电机(SPMSM)双环控制系统的建模与实现方法。该系统采用速度环一阶ADRC控制和电流环PI控制相结合的方式,旨在提高电机在复杂工况下的稳定性和响应速度。文章首先解释了选择ADRC的原因及其优势,接着展示了ADRC和PI控制器的具体实现代码,并讨论了在Matlab/Simulink环境中搭建模型的方法和注意事项。通过对不同工况下的仿真测试,验证了该控制策略的有效性,特别是在负载突变情况下的优越表现。 适合人群:从事电机控制、自动化控制及相关领域的研究人员和技术人员,尤其是对自抗扰控制感兴趣的工程师。 使用场景及目标:适用于需要高精度、高响应速度的工业伺服系统和其他高性能电机应用场景。目标是提升电机在复杂环境下的稳定性和抗扰能力,减少转速波动和恢复时间。 其他说明:文中提供了详细的代码示例和调试技巧,帮助读者更好地理解和实施该控制策略。同时,强调了在实际应用中需要注意的问题,如参数调整、输出限幅等。

    java设计模式之责任链的demo

    java设计模式之责任链的使用demo

    电力电子领域中两相交错并联Buck/Boost变换器的三种控制方式及其仿真分析

    内容概要:本文详细介绍了两相交错并联Buck/Boost变换器的硬件结构和三种控制方式(开环、电压单环、双环)的实现方法及仿真结果。文中首先描述了该变换器的硬件结构特点,即四个MOS管组成的H桥结构,两相电感交错180度工作,从而有效减少电流纹波。接着,针对每种控制方式,具体讲解了其配置步骤、关键参数设置以及仿真过程中需要注意的问题。例如,在开环模式下,通过固定PWM占空比来观察原始波形;电压单环则引入PI控制器进行电压反馈调节;双环控制进一步增加了电流内环,实现了更为精确的电流控制。此外,文章还探讨了单向结构的特点,并提供了仿真技巧和避坑指南。 适合人群:从事电力电子研究的技术人员、高校相关专业师生。 使用场景及目标:适用于希望深入了解两相交错并联Buck/Boost变换器的工作原理和技术细节的研究者,旨在帮助他们掌握不同控制方式的设计思路和仿真方法。 其他说明:文中不仅提供了详细的理论解释,还有丰富的实例代码片段,便于读者理解和实践。同时,作者分享了许多宝贵的实践经验,有助于避免常见的仿真错误。

    第十六届蓝桥杯大赛软件赛省赛第二场 C/C++ 大学 A 组

    第二场c++A组

    数控磨床编程.ppt

    数控磨床编程.ppt

    COMSOL数值模拟:N2和CO2混合气体在THM热流固三场耦合下增强瓦斯抽采的技术研究与应用

    内容概要:本文详细介绍了利用COMSOL软件进行N2和CO2混合气体在热-流-固三场耦合作用下增强煤层气抽采的数值模拟。首先,通过设定煤岩材料参数,如热导率、杨氏模量等,构建了煤岩物理模型。接着,引入达西定律和Maxwell-Stefan扩散方程,建立了混合气体运移方程,考虑了气体膨胀系数和吸附特性。在应力场求解方面,采用自适应步长和阻尼系数调整,确保模型稳定。同时,探讨了温度场与气体运移的耦合机制,特别是在低温条件下CO2注入对煤体裂隙扩展的影响。最后,通过粒子追踪和流线图展示了气体运移路径和抽采效率的变化。 适合人群:从事煤层气开采、数值模拟以及相关领域的科研人员和技术工程师。 使用场景及目标:适用于需要优化煤层气抽采工艺的研究机构和企业,旨在通过数值模拟提高抽采效率并减少环境影响。 其他说明:文中提供了详细的MATLAB和COMSOL代码片段,帮助读者理解和复现模型。此外,强调了模型参数选择和求解器配置的重要性,分享了作者的实际经验和常见问题解决方法。

    计算给定G、相位裕度、交叉频率和安全裕度要求的引线补偿器

    基于Bode的引线补偿器设计 计算给定G、相位裕度、交叉频率和安全裕度要求的引线补偿器。 计算给定电厂G、PM和Wc要求的铅补偿器,并运行ControlSystemDesigner进行验证。

    【KUKA 机器人TCP测量】:mp2_tool_fixed_en.ppt

    KUKA机器人相关文档

Global site tag (gtag.js) - Google Analytics