建立红黑树的完整可行代码(算法导论)

推荐一篇介绍红黑树的良心博客

首先要说明我学习红黑树插入时的经验:初次看时很懵逼,不要紧,放到第二天再看一遍就清楚多了,这时候开始自己把算法整理一遍。第三天再看了然于心,可以再把各种情况考虑一遍,然后就可以写代码了。必须说明的是,《算法导论》上的伪代码真的丑,显得没有什么条理,而且漏掉了几个细节,所有直接按书写的代码不经过细心调试是不能成功的。所有我推荐不看书自己写出来,肯定比看书快而且准确。

算法过程我就不介绍了,我写也不可能比上面那篇博客好。总之首先搞清楚旋转,再根据旋转过程来考虑各种情况是不会错的。我只奉上代码

  1. 输入:总数小于500的一组数字,数字之间以空格隔开,换行再CTRL+Z结束输入
  2. 输出:对建立的红黑树的中序遍历,应为顺序

代码

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
using namespace std;
#define NIL 500
#define RED 0
#define BLACK 1
int Troot=1;

void RIGHT_ROTATE(int*L,int*R,int*P,int y)//y!=NIL && L[y]!=NIL
{
    int x=L[y];int A=P[y],D=R[x];
    if(D!=NIL) P[D]=y;
    P[x]=A;
    P[y]=x;
    R[x]=y;
    L[y]=D;
    if(A!=NIL)
    {
        if(L[A]==y) L[A]=x;
        else R[A]=x;
    }
    else Troot=x;
}
void LEFT_ROTATE(int*L,int*R,int*P,int x)//x!=NIL && R[x]!=NIL
{
    int y=R[x];int A=P[x],D=L[y];
    if(D!=NIL) P[D]=x;
    P[y]=A;
    P[x]=y;
    L[y]=x;
    R[x]=D;
    if(A!=NIL)
    {
        if(L[A]==x) L[A]=y;
        else R[A]=y;
    }
    else Troot=y;
}

void RB_INSERT_FIXUP(int*KEY,int*L,int*R,int*P,bool*C,int z)
{
    while(z!=Troot && C[P[z]]==RED)
    {
        if(P[z]==L[P[P[z]]]) //父左则叔右
        {
            int y=R[P[P[z]]];//定义y为叔节点
            if(C[y]==BLACK)//如果父左叔黑
            {
                if(z==L[P[z]])//如果父左叔黑插左
                {
                    int x=P[z];
                    y=P[P[z]];//定义父亲节点为x,祖父节点为y
                    RIGHT_ROTATE(L,R,P,y);//右旋
                    C[x]=BLACK;C[y]=RED;//染色
                }
                else //如果父左叔黑插右
                {
                    int x=P[z];
                    y=P[P[z]];//定义父节点为x祖父节点为y
                    LEFT_ROTATE(L,R,P,x);//左旋父节点
                    z=x;//更新插入节点
                }
            }
            else //如果父左叔红
            {
                int x=P[z];y=P[P[z]];
                int B=R[y];//重新设定x,y和B
                C[x]=BLACK;C[B]=BLACK;C[y]=RED;
                z=y;
            }
        }
        else //父右则叔左
        {
            int y=L[P[P[z]]];
            if(C[y]==BLACK)//父右叔黑
            {
                if(z==R[P[z]])//如果父右叔黑插右
                    {
                        int x=P[P[z]];
                        y=P[z];  //按图定义x和y
                        LEFT_ROTATE(L,R,P,x);
                        C[y]=BLACK;C[x]=RED;
                    }
                    else //父右叔黑插左
                    {
                        int x=P[P[z]];
                        y=P[z];
                        RIGHT_ROTATE(L,R,P,y);
                        z=y;
                    }
            }
            else //父右叔红
            {
                int x=P[P[z]];y=P[z];//按图定义x,y
                int D=L[x];
                C[D]=BLACK;C[y]=BLACK;C[x]=RED;
                z=x;
            }
        }
     C[Troot]=BLACK;
    }
}

void RB_INSERT(int*KEY,int*L,int*R,int*P,bool*C,int N)
{
    for(int k=2;k<=N;k++)
    {
        int y=NIL,x=Troot;
        while(x!=NIL)
        {
            y=x;
            if(KEY[k]<KEY[x]) x=L[x];
            else x=R[x];
        }
        P[k]=y;
        if(KEY[k]<KEY[y]) L[y]=k;
        else R[y]=k;
        C[k]=RED;
        RB_INSERT_FIXUP(KEY,L,R,P,C,k);
    }
}

void OUT_PUT(int*KEY,int*LEFT,int*RIGHT,int k)
{
    if(LEFT[k]!=NIL) OUT_PUT(KEY,LEFT,RIGHT,LEFT[k]);
    printf("%d  ",KEY[k]);
    if(RIGHT[k]!=NIL) OUT_PUT(KEY,LEFT,RIGHT,RIGHT[k]);
}

int main()
{
int key,N=0;
queue<int>import;
 while(scanf("%d",&key)!=EOF)
 {
     N++;
     import.push(key);
 }
int *KEY=(int*)malloc(sizeof(int)*(N+2));fill(KEY,KEY+(N+2),NIL);
for(int i=1;i<=N;i++)
{
    KEY[i]=import.front();
    import.pop();
}

int *LEFT=(int*)malloc(sizeof(int)*(N+2));fill(LEFT,LEFT+(N+2),NIL);
int *RIGHT=(int*)malloc(sizeof(int)*(N+2));fill(RIGHT,RIGHT+(N+2),NIL);
int *PARENT=(int*)malloc(sizeof(int)*(N+2));fill(PARENT,PARENT+(N+2),NIL);
bool*COLOR=(bool*)malloc(sizeof(bool)*(NIL+10));fill(COLOR,COLOR+(NIL+10),BLACK);
RB_INSERT(KEY,LEFT,RIGHT,PARENT,COLOR,N);
OUT_PUT(KEY,LEFT,RIGHT,Troot);
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 我没有具体的代码,但是可以提供一些指导。红黑树的实现包括插入、搜索、删除和旋转,所以你可以考虑实现这些操作。一些可以参考的资源有:https://www.geeksforgeeks.org/red-black-tree-set-1-introduction-2/,https://www.tutorialspoint.com/data_structures_algorithms/red_black_tree_algorithm.htm,以及http://www.cs.auckland.ac.nz/software/AlgAnim/red_black.html。 ### 回答2: 红黑树(Red-Black Tree)是一种自平衡的二叉搜索树,通过在每个节点上添加一个额外的存储位表示节点的颜色(红色或黑色),并对其进行特定的调整和变色操作以保持平衡。以下是用JavaScript实现红黑树算法的示例代码: ```javascript class Node { constructor(value) { this.value = value; this.left = null; this.right = null; this.color = 1; // 默认新节点为红色(1),插入红黑树中的路径节点必须为黑色(0) this.parent = null; } } class RedBlackTree { constructor() { this.root = null; } // 左旋操作 rotateLeft(node) { const temp = node.right; node.right = temp.left; if (temp.left) { temp.left.parent = node; } temp.parent = node.parent; if (!node.parent) { this.root = temp; } else if (node === node.parent.left) { node.parent.left = temp; } else { node.parent.right = temp; } temp.left = node; node.parent = temp; } // 右旋操作 rotateRight(node) { const temp = node.left; node.left = temp.right; if (temp.right) { temp.right.parent = node; } temp.parent = node.parent; if (!node.parent) { this.root = temp; } else if (node === node.parent.right) { node.parent.right = temp; } else { node.parent.left = temp; } temp.right = node; node.parent = temp; } // 节点插入操作 insert(value) { const newNode = new Node(value); let current = this.root; let parent = null; while (current !== null) { parent = current; if (newNode.value < current.value) { current = current.left; } else { current = current.right; } } newNode.parent = parent; if (!parent) { this.root = newNode; } else if (newNode.value < parent.value) { parent.left = newNode; } else { parent.right = newNode; } if (!newNode.parent) { newNode.color = 0; return; } if (!newNode.parent.parent) { return; } this.fixTree(newNode); } // 红黑树修正 fixTree(node) { while ( node && node.parent && node.parent.color === 1 && node.color !== 0 ) { if (node.parent === node.parent.parent.left) { let uncle = node.parent.parent.right; if (uncle && uncle.color === 1) { node.parent.color = 0; uncle.color = 0; node.parent.parent.color = 1; node = node.parent.parent; } else { if (node === node.parent.right) { node = node.parent; this.rotateLeft(node); } node.parent.color = 0; node.parent.parent.color = 1; this.rotateRight(node.parent.parent); } } else { let uncle = node.parent.parent.left; if (uncle && uncle.color === 1) { node.parent.color = 0; uncle.color = 0; node.parent.parent.color = 1; node = node.parent.parent; } else { if (node === node.parent.left) { node = node.parent; this.rotateRight(node); } node.parent.color = 0; node.parent.parent.color = 1; this.rotateLeft(node.parent.parent); } } } this.root.color = 0; } } // 示例用法 const tree = new RedBlackTree(); tree.insert(7); tree.insert(3); tree.insert(18); tree.insert(10); tree.insert(22); tree.insert(8); tree.insert(11); tree.insert(26); console.log(tree.root); ``` 以上是用JavaScript实现红黑树算法的示例代码。通过调用`insert()`方法将节点插入红黑树中,该方法内部会根据红黑树的定义进行节点的调整和变色操作,最终实现自平衡的红黑树数据结构。你可以根据自己的需求,修改代码中的示例用法或扩展其功能。 ### 回答3: 红黑树是一种自平衡的二叉搜索树,它能够保持树的平衡性,从而提高搜索、插入和删除等操作的效率。下面是用 JavaScript 实现红黑树算法的简单示例代码: ```javascript // 定义红黑树的节点类 class Node { constructor(value, color) { this.value = value; this.left = null; this.right = null; this.parent = null; this.color = color; } } // 定义红黑树类 class RedBlackTree { constructor() { this.root = null; } // 左旋 rotateLeft(node) { let rightChild = node.right; node.right = rightChild.left; if (rightChild.left != null) { rightChild.left.parent = node; } rightChild.parent = node.parent; if (node.parent != null) { if (node == node.parent.left) { node.parent.left = rightChild; } else { node.parent.right = rightChild; } } else { this.root = rightChild; } rightChild.left = node; node.parent = rightChild; } // 右旋 rotateRight(node) { let leftChild = node.left; node.left = leftChild.right; if (leftChild.right != null) { leftChild.right.parent = node; } leftChild.parent = node.parent; if (node.parent != null) { if (node == node.parent.right) { node.parent.right = leftChild; } else { node.parent.left = leftChild; } } else { this.root = leftChild; } leftChild.right = node; node.parent = leftChild; } // 插入节点 insert(value) { let newNode = new Node(value, "red"); if (this.root == null) { this.root = newNode; this.root.color = "black"; return; } this.insertNode(this.root, newNode); this.enforceRBTreeProperties(newNode); } insertNode(node, newNode) { if (newNode.value < node.value) { if (node.left == null) { node.left = newNode; newNode.parent = node; } else { this.insertNode(node.left, newNode); } } else { if (node.right == null) { node.right = newNode; newNode.parent = node; } else { this.insertNode(node.right, newNode); } } } enforceRBTreeProperties(node) { if (node == this.root) { node.color = "black"; } else if (node.parent.color == "red") { let grandParent = node.parent.parent; let uncle = null; if (grandParent.left == node.parent) { uncle = grandParent.right; if (uncle != null && uncle.color == "red") { node.parent.color = "black"; uncle.color = "black"; grandParent.color = "red"; this.enforceRBTreeProperties(grandParent); } else { if (node == node.parent.right) { this.rotateLeft(node.parent); node = node.left; } node.parent.color = "black"; grandParent.color = "red"; this.rotateRight(grandParent); } } else { uncle = grandParent.left; if (uncle != null && uncle.color == "red") { node.parent.color = "black"; uncle.color = "black"; grandParent.color = "red"; this.enforceRBTreeProperties(grandParent); } else { if (node == node.parent.left) { this.rotateRight(node.parent); node = node.right; } node.parent.color = "black"; grandParent.color = "red"; this.rotateLeft(grandParent); } } } } } // 测试红黑树 let rbTree = new RedBlackTree(); rbTree.insert(10); rbTree.insert(20); rbTree.insert(30); rbTree.insert(40); // 可以继续插入其他节点并进行相关操作 ``` 这段代码实现了一个红黑树类,包括节点的定义、左右旋的操作以及插入节点时的自平衡操作。通过调用类中的 insert() 方法,可以将新的节点插入红黑树中,并自动进行相关的调整,以保持红黑树的平衡。这段代码只是一个简单示例,完整红黑树实现可能还需要考虑其他操作,比如删除节点等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值