红黑树

/*****************************************************************************************\
 * rb_tree.cpp
 * 学习 SGI STL 中的实现 《STL源码剖析》
 * 没有添加迭代器
 *
\*****************************************************************************************/

#ifndef RB_TREE_H
#define RB_TREE_H

#include <cstddef>
#include <algorithm>
#include <iostream>
#include <functional>
using namespace std ;

namespace std {

#ifdef _MSC_VER
/* 里面有VC STL内存分配之类的定义,如 allocator<> _Allocate _Construct _Destroy 等 */
#include <xmemory>  
#else
/* SGI STL 版本,包含construct destroy的定义 */
#include <strl_construct.h>
#endif


typedef bool hp_rb_tree_color_type ;
const hp_rb_tree_color_type hp_rb_tree_red = false ;
const hp_rb_tree_color_type hp_rb_tree_black = true ;

struct hp_rb_tree_node_base
{
	typedef hp_rb_tree_color_type color_type ;
	typedef hp_rb_tree_node_base* base_ptr ;

	color_type color ;
	base_ptr parent ;
	base_ptr left ;
	base_ptr right ;

	/* 后继节点,类似于迭代器中的定义 */
	static base_ptr increment( base_ptr x )
	{
		if ( x->right != 0 )
		{
			base_ptr y = x->right ;
			while ( y->left != 0 )
				y = y->left ;
			return y ;
		}
		/*
		 * 经过测试,注意这种情况:只有一个节点
		*/
		else
		{
			base_ptr p = x->parent ;
			while ( p->right == x )
			{
				x = p ;
				p = p->parent ;
			}
			if ( x->right == p )  // 只有一个节点
				return x ;
			return p ;
		}
	}

	/*  前驱节点, 类似于迭代器中的定义 */
	static base_ptr decrement( base_ptr x )   
	{
		// x == header,也就是 end()。
		if ( x->color == hp_rb_tree_red && x->parent->parent == x )
			return x->right ;

		else if ( x->left != 0 )
		{
			base_ptr y = x->left ;
			while ( y->right != 0 )
				y = y->right ;
			return y ;
		}
		else      // 仔细考虑这里,如果是mostright()节点++;返回的是header,和upper_bound一致
			      // 很强悍!
		{ 
			base_ptr p = x->parent ;  
			while ( p->left == x )
			{
				x = p ;
				p = p->parent ;
			}
			return p ;
		}
	}

	static base_ptr minimum( base_ptr x )
	{
		while ( x->left != 0 )
			x = x->left ;
		return x ;
	}

	static base_ptr maximum( base_ptr x )
	{
		while ( x->right != 0 )
			x = x->right ;
		return x ;
	}
} ;

template < typename Value >
struct hp_rb_tree_node : public hp_rb_tree_node_base
{
	// typedef __rb_tree_node* link_type ; // yes or not
	typedef hp_rb_tree_node<Value>* link_type ;         
	Value value_field ;
} ;

/* 感觉这样子定义会有很大的问题,如果对存储一种自定义的类,实例对象的大小比较
 * 依赖于某个数据成员。那么, Value类型参数不能实例成 pair,否则不能调用类的
 * 析构函数。
 * 只能把 Value 类型参数实例成自定义的类,并且重写 KeyOfValue 仿函数,取得决定
 * 类的实例大小的数据成员。
 *
 * 另外: Compare 的定义一定要符合规范
 * bool operator()( a, b ) 
 *      return a < b ;
 * 或者是 return a > b ;
 ***************************************************用sort测试,测试过,用point( x,y 二维数据 )
*/

#ifdef _MSC_VER
template < typename Key, typename Value, typename KeyOfValue, 
		   typename Compare=less<Key>, typename Alloc = allocator<Value> >
#else     // SGI STL
template < typename Key, typename Value, typename KeyOfValue, 
		   typename Compare=less<Key>, typename Alloc = alloc >
#endif
class hp_rb_tree
{
protected:
	typedef hp_rb_tree_node_base* base_ptr ;
	typedef hp_rb_tree_node<Value> rb_tree_node ;
	typedef hp_rb_tree_color_type color_type ;

	// allocator
#ifdef _MSC_VER
	typedef allocator<rb_tree_node> rb_tree_node_allocator ;
    rb_tree_node_allocator msc_alloc ;
#else
	typedef simple_alloc<rb_tree_node, Alloc> rb_tree_node_allocator ;
#endif

public:
	typedef Key key_type ;
	typedef Value value_type ;            // 如果Key 和Value不是同值的话,Value要用pair表示
	typedef value_type* pointer ;
	typedef const value_type* const_pointer ;
	typedef value_type& reference ;
	typedef const value_type& const_reference ;
	typedef rb_tree_node* link_type ;
	typedef size_t size_type ;
	// difference_type
   
protected:
    
	/* 开辟一个节点的空间 */
	link_type get_node()                
	{
#ifdef _MSC_VER	
		return msc_alloc.allocate(1) ;                // 调用operator new
#else	
		return rb_tree_node_allocator::allocate() ;   // 调用malloc
#endif
	}

	/* 释放一个节点的空间 */
	void put_node( link_type p )         
	{
#ifdef _MSC_VER	
		msc_alloc.deallocate(p,0) ;                    // 调用operator delete
#else	
		rb_tree_node_allocator::deallocate(p) ;      // 调用free
#endif
	}

	/* 构造一个节点 */
	link_type create_node( const value_type & x )  
	{
		link_type tmp = get_node() ;
#ifdef _MSC_VER	
		_Construct( &tmp->value_field, x ) ;
#else	
		construct( &tmp->value_field, x ) ;        //调用 placement new
#endif
		return tmp ;
	}

	/* 复制一个节点 */
	link_type clone_node( link_type x )            
	{
#ifdef _MSC_VER	
#else	
		link_type tmp = create_node( x->value_field ) ;
		tmp->color = x->color ;
		tmp->left = 0 ;
		tmp->right = 0 ;
		return tmp ;
#endif
	}

	/* 销毁一个节点 */
	void destroy_node( link_type p )              
	{
#ifdef _MSC_VER	
		_Destroy( &p->value_field ) ;
#else	
		destroy( &p->value_field ) ;               // 调用析构函数
#endif 
		put_node(p) ;                              // 释放节点空间       
	}

	/* 数据部分 */ 
protected:
	size_type node_count ;
	link_type header ;
	Compare key_compare ;

	link_type& root() const { return ( link_type& )header->parent ; } 

	link_type& leftmost() const { return ( link_type& )header->left ; } 

	link_type& rightmost() const { return ( link_type& ) header->right ; } 

	static link_type& left( link_type x ) { return ( link_type& ) x->left ; } 
	static link_type& right( link_type x ) { return ( link_type& ) x->right ; }
	static link_type& parent( link_type x ) { return ( link_type& ) x->parent ; }
	static reference value( link_type x ) { return x->value_field ; } 
	// 先生成临时仿函数对象KeyOfValue(),再调用operator ()
	static const Key& key( link_type x ) { return KeyOfValue()(value(x)) ; }
	static color_type& color( link_type x ) { return x->color ; }

    static link_type& left( base_ptr x ) { return ( link_type& ) x->left ; } 
	static link_type& right( base_ptr x ) { return ( link_type& ) x->right ; }
	static link_type& parent( base_ptr x ) { return ( link_type& ) x->parent ; }
	static reference value( base_ptr x ) { return x->value_field ; } 
	// 先生成临时仿函数对象KeyOfValue(),再调用operator ()
	static const Key& key( base_ptr x ) { return KeyOfValue()(value(x)) ; }
	static color_type& color( base_ptr x ) { return x->color ; }

	static link_type minimum( link_type x ) { return (link_type) __rb_tree_node_base::minimum(x) ; }
	static link_type maximum( link_type x ) { return (link_type) __rb_tree_node_base::maximum(x) ; }

private:

   /* 拷贝整棵树 */
	link_type __copy( link_type x, link_type p ) ;
	
	/* 删除整棵子树,没有平衡,被clear调用而已 */
	void __erase( link_type x ) ;

	void init()
	{
		header = get_node() ;
		color(header) = hp_rb_tree_red ;
		root() = 0 ;            // root == header->parent
		leftmost() = header ;   // leftmost: header->left
		rightmost() = header ;  // rightmost:header->right
	}
    
	/* 前驱节点 */
	link_type pre( link_type x )
	{
		return (link_type)hp_rb_tree_node_base::decrement( (base_ptr)x ) ;
	} ;
	/* 后继节点 */
	link_type next( link_type x )
	{
		//link_type pn = (link_type)hp_rb_tree_node_base::increment( (base_ptr)x ) ;
		/*
		 * 
		*/
		//if ( pn == 0 )
			//return header ;
		//return pn ;
		return (link_type)hp_rb_tree_node_base::increment( (base_ptr)x ) ;
	} ;

	/* 外部接口 */ 
public:

    
	/* 注意有默认参数,是指点仿函数的临时对象 */
	hp_rb_tree( const Compare& comp = Compare() )
		: node_count(0), key_compare(comp) { init() ; } ;           // 使用对象初始化更好

	hp_rb_tree( const hp_rb_tree<Key, Value, KeyOfValue, Compare, Alloc>& x )
		: node_count(0), key_compare(x.key_compare)
	{
		header = get_node() ;
		color(header) = hp_rb_tree_red ;
        
		if ( x.size == 0 )
		{
			root() = 0 ;
			leftmost() = 0 ;
			rightmost() = 0 ;
		}
		else
		{
			root() = __copy( x.root(), header ) ;
			leftmost() = minimum( root() ) ;
			rightmost() = maximum( root() ) ;
			node_count = x.size() ;
		}
	} ;

	/* 注意返回的是左值 */
	hp_rb_tree< Key, Value, KeyOfValue, Compare, Alloc>&
		operator= ( const hp_rb_tree< Key, Value, KeyOfValue, Compare, Alloc>& x ) ;

	~hp_rb_tree()
	{
		clear() ;
		put_node( header ) ;    // 因为header是空节点,不用调用value_field的析构函数
	} ;

	///

	// 
	/* 若要添加迭代器,可以把link_type换成迭代器 */
	pair< link_type, bool > insert_unique( const value_type& v ) ;
	/* */
	link_type insert_equal( const value_type&v ) ;
    /* */
	link_type __insert( base_ptr x, base_ptr y, const value_type& v ) ;
    
	///
	/* 查找,如果有多个相同关键字,返回最小的一个,如果没有,返回header */
	link_type find( const Key& k ) ;

	///
	/* */
	size_type erase( const Key& key ) ;
	void erase( link_type p ) ;
	
	/* 清空整棵树 */
    void clear() 
	{
		if ( node_count != 0 )
		{
			__erase( root() ) ;
            leftmost() = header ;
			rightmost() = header ;
			root() = 0 ;
			node_count = 0 ;
		}
	}

    ///
	/* 查找同一关键字 */
	pair< link_type, link_type > equal_range( const Key& k, size_type & n ) ;

	/* 注意这个函数,包含的东西很多,仔细揣摩 */
	// 返回相等关键字中“最小”的一个
	link_type lower_bound( const Key& k ) ;

	/* */
	link_type upper_bound( const Key& k ) ;

	/* 节点个数 */
	size_type size() const { return node_count ; } 

	/* 同一关键字的个数 */
	size_type count( const Key& k ) ;

	///
	/* 测试时使用,输出整棵树,写的不够好 */
    void display()
	{
		// 用层次遍历
		if ( root() == 0 )
		{
			cout << "no nodes" << endl ;
			return ;
		}
		link_type a[100], b[100] ;
		link_type *tpa, *tpb ;
		size_type cnta = 0, cntb = 0, i ;
		tpa = a ;
		tpb = b ;
		tpa[0] = root() ;
		++ cnta ;
		while ( cnta )
		{
			cntb = 0 ;

			for ( i = 0 ; i < cnta ; ++ i )
				cout << key(tpa[i]) << "--" << color( tpa[i] ) << "  " ;
			cout << endl ;

			for ( i = 0 ; i < cnta ; ++ i )
			{
				if ( tpa[i]->left != 0 )
					tpb[cntb++] = left(tpa[i]) ;
				if ( tpa[i]->right != 0 )
					tpb[cntb++] = right(tpa[i]) ;
			}
			swap( tpa, tpb ) ;
			cnta = cntb ;
		}
	} ;
} ; 

/********************************************** 成员函数外部定义 **********************************************/

#define itself hp_rb_tree<Key, Value, KeyOfValue, Compare, Alloc>
#define tmp_define template < typename Key, typename Value, typename KeyOfValue, \
		                      typename Compare, typename Alloc >

/* 拷贝整棵树 */

tmp_define
typename itself::link_type itself::__copy( link_type x, link_type p ) 
{
	link_type tmp_x = clone_node( x ) ;
	tmp_x->parent = p ;

	if ( x->right != 0 )
		tmp_x->right = __copy( x->right, tmp_x ) ;
	p = tmp_x ;
	x = left(x) ;

	// 只是递归调用构造右子树,左子树用来循环!
	while ( x!= 0 )
	{
		link_type y = clone_node(x) ;
		y->parent = p ;
		if ( y != 0 )
			y->right = __copy( right(x), y ) ;
		p = y ;
		x = left(x) ;
	}
	
	return tmp_x ;
}

/* 赋值操作符 */
tmp_define
itself& itself::operator= ( const itself& x ) 
{
	if ( this != &x )
	{
		clear() ;
		key_compare = x.key_compare ;
		if ( x.size() == 0 )
		{
			root() = 0 ;
			leftmost() = 0 ;
			rightmost() = 0 ;
		}
		else
		{
			root() = __copy( x.root(), header ) ;
			leftmost() = minimum( root() ) ;
			rightmost() = maximum( root() ) ;
			node_count = x.size() ;
		}
	}
	return *this ;
}

///
/* 插入节点操作 */
tmp_define
pair< typename itself::link_type, bool > itself::insert_unique( const value_type& v ) 
{
	link_type y = header ;
	link_type x = root() ;
	bool comp = true ;

	/* 由于没有两次判断(从而得出是否相等),所以一定要到末尾 */
	while ( x != 0 )
	{
		//cout << left(y)->value_field ;
		y = x ;
        //cout << left(x)->value_field ;
		//  注意 key_compare 的定义, 在STL中,一般定义如下:
		//  bool operator()( a, b ) { return a < b ; }
		//  又如MSDN的联机文档有:
		//  bool UDgreater ( int elem1, int elem2 )
        //  {
        //      return elem1 < elem2;   // 不是 <=
        //  }
		comp = key_compare( KeyOfValue()(v), key(x) ) ;
		x = comp ? left(x) : right(x) ;
	}
    
	/* 注意当 root() == 0 */
	link_type tmp = y ;
	if ( comp )       // v.key < x->key
	{
		if ( tmp == leftmost() )
			return pair< link_type, bool >( __insert( x, y, v ), true ) ;
		else
			tmp = pre( tmp ) ;                        // tmp 是 x 的前驱,所以有:tmp->key <= x->key, 即有 tmp->key <= v.key 
	}
    if ( key_compare( key(tmp), KeyOfValue()(v) ) )   // tmp->key < v.key
		return pair< link_type, bool >( __insert( x, y, v ), true ) ;

	return pair< link_type, bool >( tmp, false ) ;    // tmp->key == v.key

} ;

tmp_define
typename itself::link_type itself::insert_equal( const value_type&v ) 
{
	link_type y = header ;
	link_type x = root() ;
	while ( x != 0 )
	{
		y = x ;
		x = key_compare( KeyOfValue()(v), key(x) ) ? left(x) : right(x) ;
	}
	return __insert( x, y, v ) ;
} ;

/* 至今,我还不明白 x_ 有什么作用 */
tmp_define
typename itself::link_type itself::__insert( base_ptr x_, base_ptr y_, const value_type& v ) 
{
	// x 为新插入点,是空节点,x插在y的下面,y一定是叶子节点
	link_type x = ( link_type) x_ ;
	link_type y = ( link_type)y_ ;
	link_type z ;
    
	z = create_node( v ) ;
	if ( y == header || x != 0 || key_compare( KeyOfValue()(v), key(y) ) )  // x 一定等于0吧
	{
		//z = create_node( v ) ;
		left(y) = z ;
		if ( y == header )
		{
			root() = z ;
			rightmost() = z ;
		}
		else if ( y == leftmost() )
			leftmost() = z ;
	}
	else
	{
		right(y) = z ;
		if ( y == rightmost() )
			rightmost() = z ;
	}
	parent(z) = y ;
	left(z) = 0 ;
	right(z) = 0 ;

	hp_rb_tree_rebalance( z, header->parent ) ;

	return z ;
} ;

///
/* 删除节点操作 */
/* 删除同一关键字的节点,返回节点个数 */
tmp_define
typename itself::size_type itself::erase( const Key& k ) 
{
	//cout << "void itself::erase( const Key& key ) " << endl ;
	size_type n = 0 ;
    pair< link_type, link_type > first_last = equal_range( k, n ) ;
    
	/*
	// 清空整棵树
	if ( first_last.first == leftmost() && first_last.second == header )
	{
		clear() ;
		return n ;
	} 
	*/  // 先慢点用clear
    
	link_type tmp, p ;
	p = first_last.first ;
	while ( p != first_last.second )
	{
		tmp = next(p) ;
        erase( p ) ;
		p = tmp ;
	}
	//while (first != last) erase(first++);
    return n ;
}

tmp_define
void itself::erase( link_type p ) 
{
	link_type x = (link_type)hp_rb_tree_rebalance_for_erase( p, header->parent, 
		header->left, header->right ) ;         // header->parent 更好,用 root()要类型转换
    destroy_node( x ) ;
	-- node_count ;
}

/* 删除整棵子树,没有平衡,仅仅被被clear调用而已 */
tmp_define
void itself::__erase( link_type x ) 
{
	link_type tmp ;
	while ( x != 0 )
	{
		__erase( right(x) ) ;
		tmp = left(x) ;
		destroy_node( x ) ;
		x = tmp ;
	}
}
///
/* 查找,如果有多个相同关键字,返回最小的一个,如果没有,返回header */
tmp_define
typename itself::link_type find( const Key& k ) 
{
	link_type y = header ;
	link_type x = root() ;
	while ( x != 0 )
	{
		if ( !key_compare( key(x), k ) )
			y = x, x = left(x) ;
		else
			x = right(x) ;
	}
	return ( y == header || key_compare( k, key(x) ) ) ? header : y ;
}

///
/* */
tmp_define
pair< typename itself::link_type, typename itself::link_type > 
itself::equal_range( const Key& k, size_type& n ) 
{
	link_type first, last, p ;
	first = lower_bound(k) ;
	last = upper_bound(k) ;
	n = 0 ;
	for ( p = first ; p != last ; p = next(p) )
		++ n ;
	return pair<link_type, link_type>( first, last ) ;
}

/* 返回相等关键字中“最小”的一个 */
tmp_define
typename itself::link_type itself::lower_bound( const Key& k ) 
{
	link_type y = header ;
	link_type x = root() ;
    while ( x != 0 )
	{
		if ( !key_compare( key(x), k ) )
			y = x, x = left(x) ;
		else
			x = right(x) ;
	}
	return y ;
}

/* 注意STL中区间是左闭右开,返回的y是第一个大于k的节点 */
tmp_define
typename itself::link_type itself::upper_bound( const Key& k ) 
{
	/*
	link_type y = header ;
	link_type x = root() ;
	while ( x != 0 )
	{
		if ( !key_compare( k, key(x) ) )
			y = x, x = right(x) ;
		else
			x = left(x) ;
	}
	return y ;
	*/      // 这段得到的y是:“最大”的节点(关键字==k)
	link_type y = header ;
	link_type x = root() ;
	while ( x != 0 )
	{
		if ( key_compare( k, key(x) ) )
			y = x, x = left(x) ;
		else
			x = right(x) ;
	}
	/*
	  在STL中最右节点rightmost()的右节点是 header即是end();
	  但是在这里没有实现迭代器,直接返回 0 。
	*/
	//if ( y == header )
		//return (link_type)(0) ;
	return y ;
}


/********************** 全局函数*******************************************/

/* x 节点右旋, x不可能是header */
inline void hp_rb_tree_rotate_right( hp_rb_tree_node_base* x, hp_rb_tree_node_base*& root )
{
	 hp_rb_tree_node_base* y = x->left ;
	 x->left = y->right ;
	 if ( y->right != 0 )
	 {
		 y->right->parent = x ;
	 }
	 y->parent = x->parent ;
	 
	 if ( x == root )
	 {
		 root = y ;
	 }
	 else if ( x->parent->left == x )
	 {
		 x->parent->left = y ;
	 }
	 else
	 {
		 x->parent->right = y ;
	 }
	 y->right = x ;
     x->parent = y ;
} ;

/* x节点左旋 */
inline void hp_rb_tree_rotate_left( hp_rb_tree_node_base* x, hp_rb_tree_node_base*& root )
{
	hp_rb_tree_node_base* y = x->right ;
	x->right = y->left ;
	if ( y->left != 0 )
		y->left->parent = x ;
	y->parent = x->parent ;

	if ( root == x )
		root = y ;
	else if ( x->parent->left == x )
		x->parent->left = y ;
	else
		x->parent->right = y ;
	y->left = x ;
	x->parent = y ;
} ;

/* 保持红黑树的特性,加入了一个新节点 */
inline void hp_rb_tree_rebalance(hp_rb_tree_node_base* x, hp_rb_tree_node_base*& root)
{
	// x 为新插入的节点
	hp_rb_tree_node_base* y ;
	x->color = hp_rb_tree_red ;
	while ( x != root && x->parent->color == hp_rb_tree_red )
	{
		if ( x->parent == x->parent->parent->left )
		{
			y = x->parent->parent->right ;
			if ( y != 0 && y->color == hp_rb_tree_red )               // 情况1
			{
				x->parent->color = hp_rb_tree_black ;
				y->color = hp_rb_tree_black ;
				x->parent->parent->color = hp_rb_tree_red ;
				x = x->parent->parent ;
			}
			else
			{
				if ( x == x->parent->right )                  // 情况2,转移到情况3
				{
					x = x->parent ;
					hp_rb_tree_rotate_left( x, root ) ;
				}
                // 情况3: 通过变色和旋转,又转移到情况1
				x->parent->color = hp_rb_tree_black ;
				x->parent->parent->color = hp_rb_tree_red ;
				hp_rb_tree_rotate_right( x->parent->parent, root ) ;
			}
		}
		else
		{
			y = x->parent->parent->left ;
			if ( y != 0 && y->color == hp_rb_tree_red )               // 情况1
			{
				x->parent->color = hp_rb_tree_black ;
				y->color = hp_rb_tree_black ;
				x->parent->parent->color = hp_rb_tree_red ;
				x = x->parent->parent ;
			}
			else
			{
				if ( x == x->parent->left )                  // 情况2,转移到情况3
				{
					x = x->parent ;
					hp_rb_tree_rotate_right( x, root ) ;
				}
                // 情况3: 通过变色和旋转,又转移到情况1
				x->parent->color = hp_rb_tree_black ;
				x->parent->parent->color = hp_rb_tree_red ;
				hp_rb_tree_rotate_left( x->parent->parent, root ) ;
			}
		}
	}
	root->color = hp_rb_tree_black ;
} ;

/* 删除一个节点,并保持平衡 */
inline hp_rb_tree_node_base*
hp_rb_tree_rebalance_for_erase(hp_rb_tree_node_base* z,
                              hp_rb_tree_node_base*& root,
                              hp_rb_tree_node_base*& leftmost,
                              hp_rb_tree_node_base*& rightmost)
{
	hp_rb_tree_node_base* y = z ;
	hp_rb_tree_node_base* x ;
	hp_rb_tree_node_base* x_parent ;

	if ( y->left == 0 )
		x = y->right ;
	else
	{
		if ( y->right == 0 )
			x = y->left ;
		// 寻找真正要删除的节点y, z的节点不删除,只是更改value而已
		else
		{
			y = y->right ;
			while ( y->left != 0 )
				y = y->left ;
			x = y->right ;
		}
	}
    // y 只有一个孩子:x,但是 x 也可能为空
	if ( y != z )
	{
		z->left->parent = y ;
		y->left = z->left ;
		if ( z->right != y )
		{
			x_parent = y->parent ;
			if ( x != 0 )
				x->parent = x_parent ;
			y->parent->left = x ;       // y must be left of its parent
			y->right = z->right ;
			z->right->parent = y ;
		}   // 上面还未设置 y->parent
		else
			x_parent = y ;
		// 
        if ( root == z )
			root = y ;
		else if ( z->parent->left == z )
			z->parent->left = y ;
		else
			z->parent->right = y ;
		y->parent = z->parent ;
		swap( y->color, z->color ) ;

		y = z ;      // 这个要删除,destroy
	}
	else    // y == z
	{
		// 删除节点y
		x_parent = y->parent ;
		if ( x != 0 )
			x->parent = y->parent ;
		if ( root == z )
			root = x ;
		// 这里我又犯了 z->parent->left = z 的错误
		else if ( z->parent->left == z )
			z->parent->left = x ;
		else
			z->parent->right = x ;
		if ( leftmost == z )      
			if ( z->right == 0 )    // 即 x == 0 ,z为唯一节点
				leftmost = z->parent ;
			else
				// leftmost = x ;
				leftmost = hp_rb_tree_node_base::minimum(x) ;  // 很正确
		if ( rightmost == z )
			if ( z->left == 0 )    // x == 0
				rightmost = z->parent ;
			else
				rightmost = hp_rb_tree_node_base::maximum(x) ;
	}
    // y 节点需要销毁

	// 按照BST的删除性质,删除一个节点,没有平衡处理。
	// 接下来就是平衡处理。
    
	// x, x_parent 
	if ( y->color == hp_rb_tree_black )    // 如果删除的是红节点,不会改变红黑树特性
	{
		// 刚开始,删除黑色的y,则从根到 x 少了一个黑色节点。
		// 如果 x 为红色,则直接染成黑色即可。
		// 所以,x 为黑色才进入循环,则 x_parent 也定是黑色
		// 同时也可以确定,x_parent 一定存在.
		while( x != root && ( x == 0 || x->color == hp_rb_tree_black ) )
		{
			if ( x == x_parent->left )
			{
				hp_rb_tree_node_base* w = x_parent->right ;
				if ( w->color == hp_rb_tree_red )             // 情况1
				{
					w->color = hp_rb_tree_black ;
					x_parent->color = hp_rb_tree_red ;
					hp_rb_tree_rotate_left( x_parent, root ) ;
					w = x_parent->right ;
				}   // x_parent->right 一定是黑色

				// 把null节点当成黑色,则w的孩子结点都是黑色 // 情况2
				if ( ( w->left == 0 || w->left->color == hp_rb_tree_black ) 
					&& ( w->right == 0 || w->right->color == hp_rb_tree_black ) )
				{
					w->color = hp_rb_tree_red ;
					x = x_parent ;
					x_parent = x_parent->parent ;
				}
				else
				{
					// 即是 w->left 存在,且是红色         // 情况3
					if ( w->right == 0 || w->right->color == hp_rb_tree_black ) 
					{
						w->color = hp_rb_tree_red ;
						if ( w->left != 0 )                // 不用判断                  
							w->left->color = hp_rb_tree_black ;
						hp_rb_tree_rotate_right( w, root ) ;// 转移到情况4
						w = x_parent->right ;
					}
					// w->right == 红色或不存在            // 情况4
					w->color = x_parent->color ;
					x_parent->color = hp_rb_tree_black ;
					if ( w->right ) 
						w->right->color = hp_rb_tree_black ;
					hp_rb_tree_rotate_left( x_parent, root ) ;
					break ;                                // 完全符合红黑树特性!
				}
			}
			else    // swap( left, right )
			{
				hp_rb_tree_node_base* w = x_parent->left ;
				if ( w->color == hp_rb_tree_red )             // 情况1
				{
					w->color = hp_rb_tree_black ;
					x_parent->color = hp_rb_tree_red ;
					hp_rb_tree_rotate_right( x_parent, root ) ;
					w = x_parent->left ;
				}   // x_parent->right 一定是黑色

				// 把null节点当成黑色,则w的孩子结点都是黑色 // 情况2
				if ( ( w->right == 0 || w->right->color == hp_rb_tree_black ) 
					&& ( w->left == 0 || w->left->color == hp_rb_tree_black ) )
				{
					w->color = hp_rb_tree_red ;
					x = x_parent ;
					x_parent = x_parent->parent ;
				}
				else
				{
					// 即是 w->right 存在,且是红色         // 情况3
					if ( w->left == 0 || w->left->color == hp_rb_tree_black ) 
					{
						w->color = hp_rb_tree_red ;
						if ( w->right != 0 )               // 不用判断                  
							w->right->color = hp_rb_tree_black ;
						hp_rb_tree_rotate_left( w, root ) ;// 转移到情况4
						w = x_parent->left ;
					}
					// w->left == 红色或不存在            // 情况4
					w->color = x_parent->color ;
					x_parent->color = hp_rb_tree_black ;
					if ( w->left ) 
						w->left->color = hp_rb_tree_black ;
					hp_rb_tree_rotate_right( x_parent, root ) ;
					break ;                                // 完全符合红黑树特性!
				}
			}
		}
		if ( x != 0 )
			x->color = hp_rb_tree_black ;
	}
	return y ;
}

} // namespace std

#endif


/********************************************************************************************************************/
//测试代码
#include <iostream>
#include <string>
#include "rb_tree.h"
using namespace std ;

/* */
template < typename T >
class __indentity: public unary_function<T,T>
{
public:
	const T& operator()( const T& x ) const { return x ; }
} ;

template < typename Pair >     /* 实例时应该是个类似pair的类 */
class __select1st: public unary_function<Pair, typename Pair::first_type>
{
public:
	const typename Pair::first_type& operator()( const Pair& x ) const
	{
		return x.first ;
	}
} ;

class cmp
{
	bool operator()( const int & x1, const int & x2 ) const 
	{
		return x1 < x2 ;
	}
} ;

int main()
{
	/*
	hp_rb_tree< int, int, __indentity<int>, greater<int> > tree1 ;
	int n, i, x ;
	cin >> n ;
	for ( i = 0 ; i < n ; ++ i )
	{
		cin >> x ;
		tree1.insert_unique( x ) ;
	}
	tree1.display() ;
	tree1.clear() ;
	*/
	//hp_rb_tree< int, int, __indentity<int>, greater<int> > tree2 ;
   
	typedef pair<int, string> VALUE ;
    hp_rb_tree< int, VALUE, __select1st<VALUE> > tree3 ;
	//VALUE buffer[100] ;
	VALUE* p ;
	int i, n ;
	cin >> n ;
	for ( i = 0 ; i < n ; ++ i )
	{
		p = new VALUE ;
		cin >> p->first >> p->second ;
		tree3.insert_unique( *p ) ;
		delete p ;
	}
	tree3.display() ;
	tree3.clear() ;
  
	return 0 ;
}
/*
10
1 mynameishp
2 helloword
3 youaresb
4 sbsb
5 youarenotright
5 sba
6 11111
7 hphp
8 hpisasb
9 hp_hp
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值