/** * 获取红黑树中结点的后继 */ prbt_node rbt_successor(prbt_node current) { prbt_node parent = current->parent; if (current->right != nil) { return rbt_minimum(current->right); } else if (parent != nil) { while(parent != nil && parent->left != current) { current = parent; parent = parent->parent; } if (parent != nil) { return parent; } else { return nil; } } else { return nil; } }
int main(){ Rbt_tree_link a = rbt_create(); Rbtlink it; srand(time(NULL)); puts("Inserting..."); for(i=0;i<N;i++) { num[i] = rand() % N; rbt_insert(a,num[i]); } printf("rbt_size: %d\n",rbt_size(a)); printf("min value:%d max value:%d\n",rbt_item(rbt_minimum(a)),rbt_item(rbt_maximum(a))); puts("Doing assert..."); rbt_assert(a); puts("Traversing (inorder)..."); rbt_inorder(a,func); for(i=0; i < N; i++) rbt_search(a, i); puts("Traversing (from max to min)..."); it = rbt_maximum(a); for(i = rbt_size(a)-1; i >= 0; i--) { assert(n[i] == rbt_item(it)); it = rbt_predecessor(it); } printf("rbt_size: %d\n",rbt_size(a)); puts("Deleting all values..."); int i = 0; for (i = 0; i < N; ++i) { printf("%d deleted\r", num[i]); rbt_delete(a, num[i]); } puts("\nDestroying rbt.."); rbt_destroy(a); puts("OK!"); return 0; }
RBT_NODE *rbt_successor( RBT_ROOT *root , RBT_NODE *x ) { if ( x != &( root->nil ) ) { if ( x->right != &( root->nil ) ) { return rbt_minimum( root , x->right ) ; } else { RBT_NODE *y = x->p ; while ( y != &( root->nil ) && x == y->right ) { x = y ; y = y->p ; } return y ; } } return NULL ; }