我有一个简单的红黑树实现。我想打印最后一级这个树的节点。我知道我的树有15个节点。所以我想要树的3级。如果我为节点放置索引并找到他们如何做这项工作?还是以另一种方式存在?
typedef enum {RED, BLACK} nodecolor ;
struct node{
node * left;
node * right;
node * parent;
node * nil;
node * root;
int * key;
nodecolor color;
};
node *root=NULL;
void LeftRotate(node* &tree, node* x){
node* y;
node* nil=tree->nil;
y=x->right;
x->right=y->left;
if (y->left != nil)
y->left->parent=x;
y->parent=x->parent;
if(x==x->parent->left)
x->parent->left=y;
else
x->parent->right=y;
y->left=x;
x->parent=y;
}
void RightRotate(node* &tree, node* y){
node* x;
node* nil=tree->nil;
x=y->left;
y->left=x->right;
if (nil != x->right)
x->right->parent=y;
x->parent=y->parent;
if( y == y->parent->left)
y->parent->left=x;
else
y->parent->right=x;
x->right=y;
y->parent=x;
}
void InsertFixUp(node * &tree, node *z){
node *nil=tree->nil;
node *y;
while (z->parent->color==RED){
if(z->parent==z->parent->parent->left){
y=z->parent->parent->right;
if(y->color==RED){
z->parent->color=BLACK;
y->color=BLACK;
z->parent->parent->color=RED;
z=z->parent->parent;
}
else if(z=z->parent->right){
z=z->parent;
LeftRotate(tree,z);
}
z->parent->color=BLACK;
z->parent->parent->color=RED;
RightRotate(tree,z->parent->parent);
}
else{
y=z->parent->parent->left;
if(y->color==RED){
z->parent->color=BLACK;
y->color=BLACK;
z->parent->parent->color=RED;
z=z->parent->parent;
}
else if(z=z->parent->left){
z=z->parent;
LeftRotate(tree,z);
}
z->parent->color=BLACK;
z->parent->parent->color=RED;
RightRotate(tree,z->parent->parent);
}
}
}
void Insert(node *&tree,node*&z){
node* nil=tree->nil;
node* root=tree->root;
node *y;
node *x;
y=tree->nil;
x=tree->root;
while(x!=tree->nil){
y=x;
if((z->key)<(x->key))
x=x->left;
else
x=x->right;
}
y=z->parent;
if(y=tree->nil)
z=tree->root;
else if((z->key)<(y->key))
z=y->left;
else
z=y->right;
z->left=tree->nil;
z->right=tree->nil;
z->color=RED;
InsertFixUp(tree,z);
}
答案 0 :(得分:2)
如果我正确理解了这个问题,那么这样的事情对你有用:
void printNode( node *n ){
if( n->left == NULL && node->right == NULL ){
printf( "node info: %d\n" n->key);
return;
}
if( n->left != NULL )
printNode( n->left );
if( n->right != NULL );
printNode( n->right );
}
请注意:它不是经过测试的代码。我的想法是使用关于没有后代的节点的递归函数打印信息遍历整个树(最后一级)
我使用了NULL
,您的代码中可能会使用nil
(您可能需要根据自己的需要进行调整)。