【愚公系列】2021年11月 C#版 数据结构与算法解析(红黑树)

简介: 【愚公系列】2021年11月 C#版 数据结构与算法解析(红黑树)

红黑树定义:它或者是一颗空树,或者是具有一下性质的二叉查找树


1):每个节点或是红的,或是黑的。


2):根节点是黑的。


3):每个叶节点(NIL)是黑的。(所有NULL结点称为叶子节点,且认为颜色为黑)


4):如果一个节点是红的,则他的两个子节点是黑的。


5):对每个节点,从该节点到其子孙节点的所有路径上包含相同数目的黑节点。

image.png

红黑树用在关联数组、字典的实现上。需du要的空间zhi比散列表小。 任何键值对应,需要dao随机存储和键有序的情况都可以用。

class TreeNode<T>
    {
        public T Data { get; set; }
        public TreeNode<T> LeftChild { get; set; }
        public TreeNode<T> RightChild { get; set; }
        public TreeNode<T> Parent { get; set; }
        public int Color { get; set; }
        public TreeNode(T data)
        {
            Data = data;
            Parent = null;
            LeftChild = null;
            RightChild = null;
        }
        public TreeNode(T newData, TreeNode<T> parent)
        {
            Data = newData;
            Parent = parent;
            LeftChild = null;
            RightChild = null;
        }
    }
    internal class RedBlackTree<T> where T : IComparable<T>, IEquatable<T>, new()
    {
        public TreeNode<T> Root { get; private set; }
        public int Size { get; private set; }
        public RedBlackTree()
        {
            Root = null;
            Size = 0;
        }
        private static TreeNode<T> Add(TreeNode<T> to, TreeNode<T> newNode)
        {
            if (newNode.Data.CompareTo(to.Data) < 0)
            {
                if (to.LeftChild != null) return Add(to.LeftChild, newNode);
                newNode.LeftChild = null;
                newNode.RightChild = null;
                to.LeftChild = newNode;
                newNode.Color = 1;
                newNode.Parent = to;
                return newNode;
            }
            if (to.RightChild != null) return Add(to.RightChild, newNode);
            newNode.LeftChild = null;
            newNode.RightChild = null;
            to.RightChild = newNode;
            newNode.Color = 1;
            newNode.Parent = to;
            return newNode;
        }
        private void LeftTurn(TreeNode<T> node)
        {
            if (node.RightChild == null) return;
            var child = node.RightChild;
            node.RightChild = child.LeftChild;
            if (child.LeftChild != null) child.LeftChild.Parent = node;
            child.Parent = node.Parent;
            if (node.Parent == null) Root = child;
            else
            {
                if (node == node.Parent.LeftChild)
                    node.Parent.LeftChild = child;
                else
                    node.Parent.RightChild = child;
            }
            child.LeftChild = node;
            node.Parent = child;
        }
        private void RightTurn(TreeNode<T> node)
        {
            if (node.LeftChild == null) return;
            var child = node.LeftChild;
            node.LeftChild = child.RightChild;
            if (child.RightChild != null) child.RightChild.Parent = node;
            child.Parent = node.Parent;
            if (node.Parent == null) Root = child;
            else
            {
                if (node == node.Parent.RightChild) node.Parent.RightChild = child;
                else node.Parent.LeftChild = child;
            }
            child.RightChild = node;
            node.Parent = child;
        }
        public void Insert(TreeNode<T> node)
        {
            if (Root == null)
            {
                Root = node;
                Root.Color = 0;
                Root.LeftChild = null;
                Root.RightChild = null;
                Root.Parent = null;
            }
            else
            {
                var addedNode = Add(Root, node);
                while (addedNode != Root && addedNode.Parent.Color == 1)
                {
                    if (addedNode.Parent == addedNode.Parent.Parent.LeftChild)
                    {
                        var y = addedNode.Parent.Parent.RightChild;
                        if (y != null && y.Color == 1)
                        {
                            addedNode.Parent.Color = 0;
                            y.Color = 0;
                            addedNode.Parent.Parent.Color = 1;
                            addedNode = addedNode.Parent.Parent;
                        }
                        else
                        {
                            if (addedNode == addedNode.Parent.RightChild)
                            {
                                addedNode = addedNode.Parent;
                                LeftTurn(addedNode);
                            }
                            addedNode.Parent.Color = 0;
                            addedNode.Parent.Parent.Color = 1;
                            RightTurn(addedNode.Parent.Parent);
                        }
                    }
                    else
                    {
                        var y = addedNode.Parent.Parent.LeftChild;
                        if (y != null && y.Color == 1)
                        {
                            addedNode.Parent.Color = 0;
                            y.Color = 0;
                            addedNode.Parent.Parent.Color = 1;
                            addedNode = addedNode.Parent.Parent;
                        }
                        else
                        {
                            if (addedNode == addedNode.Parent.Parent.LeftChild)
                            {
                                addedNode = addedNode.Parent;
                                RightTurn(addedNode);
                            }
                            addedNode.Parent.Color = 0;
                            addedNode.Parent.Parent.Color = 1;
                            LeftTurn(addedNode.Parent.Parent);
                        }
                    }
                }
            }
            Root.Color = 0;
        }
        private static TreeNode<T> Min(TreeNode<T> node)
        {
            while (node.LeftChild != null) node = node.LeftChild;
            return node;
        }
        private static TreeNode<T> Next(TreeNode<T> node)
        {
            if (node.RightChild != null) return Min(node.RightChild);
            var y = node.Parent;
            while (y != null && node == y.RightChild)
            {
                node = y;
                y = y.Parent;
            }
            return y;
        }
        private void FixUp(TreeNode<T> node)
        {
            while (node != Root && node.Color == 0)
            {
                if (node == node.Parent.LeftChild)
                {
                    var w = node.Parent.RightChild;
                    if (w.Color == 1)
                    {
                        w.Color = 0;
                        node.Parent.Color = 1;
                        LeftTurn(node.Parent);
                        w = node.Parent.RightChild;
                    }
                    if (w.LeftChild.Color == 0 && w.RightChild.Color == 0)
                    {
                        w.Color = 1;
                        node = node.Parent;
                    }
                    else
                    {
                        if (w.RightChild.Color == 0)
                        {
                            w.LeftChild.Color = 0;
                            w.Color = 1;
                            RightTurn(w);
                            w = node.Parent.RightChild;
                        }
                        w.Color = node.Parent.Color;
                        node.Parent.Color = 0;
                        w.RightChild.Color = 0;
                        LeftTurn(node.Parent);
                        node = Root;
                    }
                }
                else
                {
                    var w = node.Parent.LeftChild;
                    if (w.Color == 1)
                    {
                        w.Color = 0;
                        node.Parent.Color = 1;
                        RightTurn(node.Parent);
                        w = node.Parent.LeftChild;
                    }
                    if (w.RightChild.Color == 0 && w.LeftChild.Color == 0)
                    {
                        w.Color = 1;
                        node = node.Parent;
                    }
                    else
                    {
                        if (w.LeftChild.Color == 0)
                        {
                            w.RightChild.Color = 0;
                            w.Color = 1;
                            LeftTurn(w);
                            w = node.Parent.LeftChild;
                        }
                        w.Color = node.Parent.Color;
                        node.Parent.Color = 0;
                        w.LeftChild.Color = 0;
                        RightTurn(node.Parent);
                        node = Root;
                    }
                }
            }
            node.Color = 0;
        }
        public void Delete(TreeNode<T> node)
        {
            TreeNode<T> y;
            if (node.LeftChild == null || node.RightChild == null)
                y = node;
            else
                y = Next(node);
            var x = y.LeftChild ?? y.RightChild;
            if (x == null)
            {
                node.Data = y.Data;
                if (y.Parent == null) return;
                if (y.Parent.LeftChild == y) y.Parent.LeftChild = null;
                else y.Parent.RightChild = null;
                return;
            }
            x.Parent = y.Parent;
            if (y.Parent == null) Root = x;
            else
            {
                if (y == y.Parent.LeftChild) y.Parent.LeftChild = x;
                else y.Parent.RightChild = x;
            }
            if (y != node)
            {
                node.Data = y.Data;
            }
            if (y.Color == 0) FixUp(x);
        }
        private static TreeNode<T> SearchInSubTree(TreeNode<T> topNode, T data)
        {
            if (data.Equals(topNode.Data))
                return topNode;
            if (data.CompareTo(topNode.Data) < 0 && topNode.LeftChild != null)
                return SearchInSubTree(topNode.LeftChild, data);
            if (data.CompareTo(topNode.Data) > 0 && topNode.RightChild != null)
                return SearchInSubTree(topNode.RightChild, data);
            return null;
        }
        public bool Search(T data)
        {
            return SearchInSubTree(Root, data) != null;
        }
        public TreeNode<T> SearchNode(T data)
        {
            return SearchInSubTree(Root, data);
        }
        public IEnumerator<T> GetEnumerator()
        {
            if (Root == null)
                yield break;
            var current = Min(Root);
            yield return current.Data;
            while (Next(current) != null)
            {
                current = Next(current);
                yield return current.Data;
            }
        }
        public IEnumerator<TreeNode<T>> DfsEnum()
        {
            var verts = new Stack<TreeNode<T>>();
            if (Root == null)
                yield break;
            verts.Push(Root);
            var previous = 0;
            while (verts.Count != 0)
            {
                var current = verts.Peek();
                if (current.LeftChild == null && current.RightChild == null)
                {
                    verts.Pop();
                    yield return current;
                    if (current.Parent != null)
                        previous = current == current.Parent.LeftChild ? 1 : 2;
                    else
                        yield break;
                    continue;
                }
                switch (previous)
                {
                    case 0:
                        if (current.LeftChild == null)
                        {
                            previous = 1;
                            continue;
                        }
                        verts.Push(current.LeftChild);
                        previous = 0;
                        break;
                    case 1:
                        if (current.RightChild == null)
                        {
                            verts.Pop();
                            yield return current;
                            if (current.Parent != null)
                            {
                                previous = current == current.Parent.LeftChild ? 1 : 2;
                                continue;
                            }
                            yield break;
                        }
                        verts.Push(current.RightChild);
                        previous = 0;
                        break;
                    case 2:
                        verts.Pop();
                        yield return current;
                        if (current.Parent != null)
                            previous = current == current.Parent.LeftChild ? 1 : 2;
                        else
                            yield break;
                        break;
                }
            }
        }
        public IEnumerator<TreeNode<T>> BfsEnum()
        {
            var verts = new Queue<TreeNode<T>>();
            verts.Enqueue(Root);
            while (verts.Count != 0)
            {
                var current = verts.Dequeue();
                yield return current;
                if (current.LeftChild != null)
                    verts.Enqueue(current.LeftChild);
                if (current.RightChild != null)
                    verts.Enqueue(current.RightChild);
            }
        }
    }

image.png

image.png


相关文章
|
5月前
|
存储 人工智能 算法
从零掌握贪心算法Java版:LeetCode 10题实战解析(上)
在算法世界里,有一种思想如同生活中的"见好就收"——每次做出当前看来最优的选择,寄希望于通过局部最优达成全局最优。这种思想就是贪心算法,它以其简洁高效的特点,成为解决最优问题的利器。今天我们就来系统学习贪心算法的核心思想,并通过10道LeetCode经典题目实战演练,带你掌握这种"步步为营"的解题思维。
|
6月前
|
机器学习/深度学习 人工智能 搜索推荐
从零构建短视频推荐系统:双塔算法架构解析与代码实现
短视频推荐看似“读心”,实则依赖双塔推荐系统:用户塔与物品塔分别将行为与内容编码为向量,通过相似度匹配实现精准推送。本文解析其架构原理、技术实现与工程挑战,揭秘抖音等平台如何用AI抓住你的注意力。
1614 7
从零构建短视频推荐系统:双塔算法架构解析与代码实现
|
6月前
|
XML 前端开发 C#
C#编程实践:解析HTML文档并执行元素匹配
通过上述步骤,可以在C#中有效地解析HTML文档并执行元素匹配。HtmlAgilityPack提供了一个强大而灵活的工具集,可以处理各种HTML解析任务。
323 19
|
6月前
|
机器学习/深度学习 存储 算法
动态规划算法深度解析:0-1背包问题
0-1背包问题是经典的组合优化问题,目标是在给定物品重量和价值及背包容量限制下,选取物品使得总价值最大化且每个物品仅能被选一次。该问题通常采用动态规划方法解决,通过构建二维状态表dp[i][j]记录前i个物品在容量j时的最大价值,利用状态转移方程避免重复计算子问题,从而高效求解最优解。
738 1
|
6月前
|
算法 搜索推荐 Java
贪心算法:部分背包问题深度解析
该Java代码基于贪心算法求解分数背包问题,通过按单位价值降序排序,优先装入高价值物品,并支持部分装入。核心包括冒泡排序优化、分阶段装入策略及精度控制,体现贪心选择性质,适用于可分割资源的最优化场景。
427 1
贪心算法:部分背包问题深度解析
|
6月前
|
机器学习/深度学习 边缘计算 人工智能
粒子群算法模型深度解析与实战应用
蒋星熠Jaxonic是一位深耕智能优化算法领域多年的技术探索者,专注于粒子群优化(PSO)算法的研究与应用。他深入剖析了PSO的数学模型、核心公式及实现方法,并通过大量实践验证了其在神经网络优化、工程设计等复杂问题上的卓越性能。本文全面展示了PSO的理论基础、改进策略与前沿发展方向,为读者提供了一份详尽的技术指南。
粒子群算法模型深度解析与实战应用
|
6月前
|
机器学习/深度学习 资源调度 算法
遗传算法模型深度解析与实战应用
摘要 遗传算法(GA)作为一种受生物进化启发的优化算法,在复杂问题求解中展现出独特优势。本文系统介绍了GA的核心理论、实现细节和应用经验。算法通过模拟自然选择机制,利用选择、交叉、变异三大操作在解空间中进行全局搜索。与梯度下降等传统方法相比,GA不依赖目标函数的连续性或可微性,特别适合处理离散优化、多目标优化等复杂问题。文中详细阐述了染色体编码、适应度函数设计、遗传操作实现等关键技术,并提供了Python代码实现示例。实践表明,GA的成功应用关键在于平衡探索与开发,通过精心调参维持种群多样性同时确保收敛效率
机器学习/深度学习 算法 自动驾驶
1178 0
|
6月前
|
机器学习/深度学习 人工智能 资源调度
大语言模型的核心算法——简要解析
大语言模型的核心算法基于Transformer架构,以自注意力机制为核心,通过Q、K、V矩阵动态捕捉序列内部关系。多头注意力增强模型表达能力,位置编码(如RoPE)解决顺序信息问题。Flash Attention优化计算效率,GQA平衡性能与资源消耗。训练上,DPO替代RLHF提升效率,MoE架构实现参数扩展,Constitutional AI实现自监督对齐。整体技术推动模型在长序列、低资源下的性能突破。
735 8
|
6月前
|
算法 API 数据安全/隐私保护
深度解析京东图片搜索API:从图像识别到商品匹配的算法实践
京东图片搜索API基于图像识别技术,支持通过上传图片或图片URL搜索相似商品,提供智能匹配、结果筛选、分页查询等功能。适用于比价、竞品分析、推荐系统等场景。支持Python等开发语言,提供详细请求示例与文档。

热门文章

最新文章

推荐镜像

更多
  • DNS