• 红黑树插入代码学习


    算法导论的伪代码的注释看的很晕啊,网上找到代码,研究下:

    代码
    void rb_tree_insert(rb_tree * &T, int value)
    {
    rb_tree
    *z = new rb_tree();
    z
    ->data = value;//即将插入的节点
    rb_tree *y = nil;
    rb_tree
    *x = T;
    while (x != nil)
    {
    y
    = x;
    if(x->data > z->data)
    x
    = x->left;
    else
    x
    = x->right;
    }
    z
    ->parent = y;
    if(y == nil)
    T
    = z;
    else
    {
    if (z->data < y->data)
    {
    y
    ->left = z;
    }
    else
    {
    y
    ->right = z;
    }
    }
    z
    ->left = z->right = nil;
    z
    ->color = red;
    }

    rb_tree
    * rb_insert_fixup(rb_tree *T, rb_tree *z)
    {
    rb_tree
    *y = NULL;
    while(z != T && z->parent->color == red)//z不是根节点而且父节点为红
    {
    if (z->parent == z->parent->parent->left)//父节点是祖父节点的左子树
    {
    y
    = z->parent->parent->left;//y为z的叔节点
    if(y && y->color == red)//叔节点存在而且为红
    {
    z
    ->parent->color = black;//更改父节点为黑
    y->color = black;//叔节点也改为黑
    z->parent->parent->color = red;//祖父节点改为红
    z = z->parent->parent;//z上升至祖父节点继续迭代确保红黑树的性质
    }
    else //无叔节点或者叔节点为黑
    {
    if (z == z->parent->right)//如果新节点是父节点的右子树
    {
    z
    = z->parent;
    left_rotate(z);
    }
    z
    ->parent->color = black;//父节点改为黑色
    z->parent->parent->color = red;//祖父节点改为红色
    right_rotate(z->parent->parent);
    }
    }
    else
    {
    y
    = z->parent->parent->right;//y为z的叔节点
    if(y && y->color == red)//叔节点存在而且为红
    {
    z
    ->parent->color = black;//更改父节点为黑
    y->color = black;//叔节点也改为黑
    z->parent->parent->color = red;//祖父节点改为红
    z = z->parent->parent;//z上升至祖父节点继续迭代确保红黑树的性质
    }
    else //无叔节点或者叔节点为黑
    {
    if (z == z->parent->left)//如果新节点是父节点的右子树
    {
    z
    = z->parent;
    right_rotate(z);
    }
    z
    ->parent->color = black;//父节点改为黑色
    z->parent->parent->color = red;//祖父节点改为红色
    left_rotate(z->parent->parent);
    }
    }
    }
    T
    ->color = black;
    return T;
    }

  • 相关阅读:
    驱动程序细节和权衡
    交互
    查找UI元素
    Selenium-Webdriver API命令和操作-Get & Wait
    Selenium的webdriver
    openssl生成ssl证书
    tony_nginx_02_URL重写
    CPA
    消息队列产品比较
    元数据交换绑定的秘密
  • 原文地址:https://www.cnblogs.com/xiangshancuizhu/p/1899468.html
Copyright © 2020-2023  润新知