算法 – 使用Delphi的Tomes中的红黑树实现Promote()的问题

前端之家收集整理的这篇文章主要介绍了算法 – 使用Delphi的Tomes中的红黑树实现Promote()的问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用Julian Bucknall在他着名的着作“ The Tomes Of Delphi”中写的Red-Black树实现.源代码可以是 downloaded here,我在Delphi 2010中使用了代码,并且修改了TdBasics.pas,让它在Delphi的现代版本中进行编译(主要是将其大部分评论出来 – 树代码只需要一些定义)

这是着名作家在一本经常推荐的书中着名的实施.我觉得我应该使用它坚实的地面.但是我遇到使用Delete()和Promote()的崩溃.用DUnit回退写单元测试,这些问题很容易重现.一些示例代码是(我的DUnit测试的片段):

  1. // Tests that require an initialised tree start with one with seven items
  2. const
  3. NumInitialItems : Integer = 7;
  4.  
  5. ...
  6.  
  7. // Data is an int,not a pointer
  8. function Compare(aData1,aData2: Pointer): Integer;
  9. begin
  10. if NativeInt(aData1) < NativeInt(aData2) then Exit(-1);
  11. if NativeInt(aData1) > NativeInt(aData2) then Exit(1);
  12. Exit(0);
  13. end;
  14.  
  15. // Add seven items (0..6) to the tree. Node.Data is a pointer field,just cast.
  16. procedure TestTRedBlackTree.SetUp;
  17. var
  18. Loop : Integer;
  19. begin
  20. FRedBlackTree := TtdRedBlackTree.Create(Compare,nil);
  21. for Loop := 0 to NumInitialItems - 1 do begin
  22. FRedBlackTree.Insert(Pointer(Loop));
  23. end;
  24. end;
  25.  
  26. ...
  27.  
  28. // Delete() crashes for the first item,no matter if it is 0 or 1 or...
  29. procedure TestTRedBlackTree.TestDelete;
  30. var
  31. aItem: Pointer;
  32. Loop : Integer;
  33. begin
  34. for Loop := 1 to NumInitialItems - 1 do begin // In case 0 (nil) causes problems,but 1 fails too
  35. aItem := Pointer(Loop);
  36. Check(FRedBlackTree.Find(aItem) = aItem,'Item not found before deleting');
  37. FRedBlackTree.Delete(aItem);
  38. Check(FRedBlackTree.Find(aItem) = nil,'Item found after deleting');
  39. Check(FRedBlackTree.Count = NumInitialItems - Loop,'Item still in the tree');
  40. end;
  41. end;

我不够坚实的算法知道如何解决它,而不会引入更多的问题(不平衡或不正确的树).我知道,因为我已经尝试了:)

崩溃的代码

上述测试在Promote()中失败时删除一个项目,在行上标记了!!!:

  1. function TtdRedBlackTree.rbtPromote(aNode : PtdBinTreeNode)
  2. : PtdBinTreeNode;
  3. var
  4. Parent : PtdBinTreeNode;
  5. begin
  6. {make a note of the parent of the node we're promoting}
  7. Parent := aNode^.btParent;
  8.  
  9. {in both cases there are 6 links to be broken and remade: the node's
  10. link to its child and vice versa,the node's link with its parent
  11. and vice versa and the parent's link with its parent and vice
  12. versa; note that the node's child could be nil}
  13.  
  14. {promote a left child = right rotation of parent}
  15. if (Parent^.btChild[ctLeft] = aNode) then begin
  16. Parent^.btChild[ctLeft] := aNode^.btChild[ctRight];
  17. if (Parent^.btChild[ctLeft] <> nil) then
  18. Parent^.btChild[ctLeft]^.btParent := Parent;
  19. aNode^.btParent := Parent^.btParent;
  20. if (aNode^.btParent^.btChild[ctLeft] = Parent) then //!!!
  21. aNode^.btParent^.btChild[ctLeft] := aNode
  22. else
  23. aNode^.btParent^.btChild[ctRight] := aNode;
  24. aNode^.btChild[ctRight] := Parent;
  25. Parent^.btParent := aNode;
  26. end
  27. ...

Parent.btParent(成为aNode.btParent)为零,因此崩溃.检查树结构,节点的父节点是根节点,它显然具有一个零个父本身.

一些非工作的尝试修复它

我尝试简单地测试这个,只有当祖父母存在时才运行if / then / else语句.虽然这似乎是合乎逻辑的,但这是一个天真的修复;我不明白旋转是否足以知道这是否有效,或者是否应该发生其他事情 – 而这样做会导致另一个问题,在片段之后提到. (请注意,以下复制的代码在上面复制的代码片段左旋,同样的错误也发生在那里.)

  1. if aNode.btParent <> nil then begin //!!! Grandparent doesn't exist,because parent is root node
  2. if (aNode^.btParent^.btChild[ctLeft] = Parent) then
  3. aNode^.btParent^.btChild[ctLeft] := aNode
  4. else
  5. aNode^.btParent^.btChild[ctRight] := aNode;
  6. aNode^.btChild[ctRight] := Parent;
  7. end;
  8. Parent^.btParent := aNode;
  9. ...

使用此代码,删除测试仍然失败,但更奇怪的是:调用Delete()后,对Find()的调用正确返回nil,表示该项被删除.但是,循环的最后一次迭代,删除项目6导致TtdBinarySearchTree.bstFindItem中的崩溃:

  1. Walker := FBinTree.Root;
  2. CmpResult := FCompare(aItem,Walker^.btData);

FBinTree.Root为零,调用FCompare时崩溃.

所以 – 在这一点上,我可以告诉我的修改显然只是造成更多的问题,而另一些更根本的是实现算法的代码错误的.不幸的是,即使有这本书作为参考,我也不能弄清楚出了什么问题,或者说,正确的实现是什么样的,这里有什么不同.

我本来以为一直是我的代码不正确地使用树,导致问题.这还是很可能的!作者,这本书,因此隐含的代码在德尔福世界是众所周知的.但是崩溃是很容易重现的,使用从作者的网站下载的本书的源代码,为课程编写一些非常基本的单元测试.其他人也必须在过去十年的某个时候使用这个代码,并遇到同样的问题(除非是我的错误,我的代码和单元测试都使用不正确的树).我正在寻求帮助的答案:

>识别和修复“推广”和课堂其他地方的任何错误.请注意,我还为基类TtdBinarySearchTree编写了单元测试,并且全部通过. (这并不意味着它是完美的 – 我可能没有发现失败的案例,但这是一些帮助.)
>查找代码的更新版本.朱利安还没有发表任何errata for the red-black tree implementation.
>如果一切都失败,找到一个不同的,已知的很好的Delphi红黑树实现.我正在使用树来解决一个问题,而不是为了写一棵树.如果我不得不,我会很乐意用另一个(给定的许可条款等)来替换潜在的实现.然而,鉴于这本书和代码的谱系,问题是令人惊讶的,解决它们会帮助更多的人而不仅仅是我 – 这是一个广泛推荐的书在Delphi社区.

编辑:进一步说明

评论家MBo指出朱利安的EZDSL library,其中包含一个红黑树的另一个实现.该版本通过单元测试.我目前正在比较两个来源,试图看看算法偏离哪里,找出错误.

一种可能性是简单地使用EZDSL红黑树,而不是德尔福红黑树的Tomes,但图书馆有一些问题,使我不热衷于使用它:它仅用于32位x86;一些方法仅在汇编中提供,而不是Pascal(虽然大多数有两个版本);树结构完全不同,例如使用光标到节点而不是指针 – 一个完全有效的方法,但是代码与ToD书中的“示例”代码的不同之处的示例,其中导航在语义上是不同的;在我看来,代码很难理解和使用:它是非常重要的优化,变量和方法不如清楚地命名,有各种魔术功能,节点结构实际上是一个联合/案例记录,压缩详细的堆栈,队列,出列和列表,双链表,跳过列表,树,二进制树和堆在一个结构中几乎不可理解的调试器等.它不是代码我很想在生产中使用在哪里我需要支持它,也不容易学习. Delphi源代码的Tomes可读性更好,可维护性更高…但也不正确.你看到困境:)

我试图比较代码来尝试找到朱利安的实践代码(EZDSL)和他的教学代码(德尔福的Tomes)之间的区别.但是这个问题仍然是开放的,我仍然会感谢你的答案.自从发布以来的十二年里,我不可能是唯一一个使用来自德尔福的墓的红黑树的人:)

编辑:进一步说明

我已经回答了这个问题(尽管提供了一个赏金,哎呀),我很难通过检查代码和与算法的ToD描述进行比较来找到错误,所以我根据一个好的页面重新实现了有缺陷的方法描述了麻省理工学院许可的C实施的结构;详情如下.一个好处是,我认为新的实现实际上更清楚了解.

解决方法

我没有想出通过检查Delphi源代码的Tomes和比较算法或Julian的其他实现,大量优化的EZDSL库实现(因此这个问题!),但是我重新实现了删除,并且为了很好的测量也插入,基于示例 C code for a red-black tree on the Literate Programming site,我发现一个红黑树的最清楚的例子之一. (实际上,通过研究代码并验证它是否正确地实现了某些错误,尤其是在您不完全理解算法的时候,其实很难找到一个bug,我可以告诉你,现在我有了更好的理解!)树有很好的记录 – 我认为Delphi的Tomes更好地概述了为什么树的工作原理,但是这个代码是可读实现的一个更好的例子.

注意事项:

>评论通常是页面对特定方法的解释的直接引用.
>这是很容易的移植,虽然我把程序化的C代码移植到面向对象的结构.有一些小小的怪癖,如Bucknall的树有一个FHead节点,孩子是树的根,你必须注意转换. (如果节点的父节点为NULL,则经常测试测试节点是根节点的方法,我已经将这个和其他类似的逻辑提取到帮助方法,或者节点或树方法).
>读者也可能发现Eternally Confuzzled page on red-black trees有用.虽然我在编写这个实现时没有使用它,但我可能应该有,如果在这个实现中有错误,我将转向那里了解.这也是我在调查ToD时研究RB树的第一个页面,提到红黑树和2-3-4 trees之间的连接名称.
>如果不清楚,这段代码修改了Delphi中的Tomes示例TtdBinaryTree,TtdBinarySearchTree和TtdRedBlackTree在TDBinTre.pas(source code download on the ToD page)中找到.要使用它,请编辑该文件.这不是一个新的实现,而是不完整的.具体来说,它保持ToD代码的结构,例如TtdBinarySearchTree不是TtdBinaryTree的后代,而是拥有一个作为成员(即包装它),使用FHead节点而不是Root的零父项等.
>原始代码是MIT许可的. (该网站正在转移到另一个许可证;它可能已经更改了您检查的时间.对于未来的读者,在撰写本文时,代码肯定是在麻省理工学院的许可证下.)我不确定对Tomes的许可的Delphi代码;因为它在一本算法书中,假设你可以使用它可能是合理的 – 它在参考书中是隐含的,我认为.就我而言,只要你符合原始许可证,欢迎使用它:)请留下评论,如果它是有用的,我想知道.
> Delphi实现的Tomes通过使用祖先排序的二叉树插入方法进行插入,然后“促进”节点.逻辑在这两个地方.该实现也实现插入,然后进入多个情况来检查位置并通过显式轮换进行修改.这些旋转是单独的方法(RotateLeft和RotateRight),我觉得很有用 – ToD代码谈论旋转,但没有明确地将它们拉到单独的命名方法.删除是类似的:它进入一些情况.每个案例都在页面上解释,并在我的代码中作为注释.其中一些我命名,但有些太复杂,不能放入一个方法名称,所以只是“案例4”,“案例5”等,并有注释解释.
>该页面还有代码来验证树的结构,以及红黑属性.我已经开始做这个作为单元测试的一部分,但还没有完全添加所有的红黑树约束,所以也添加了这个代码到树.它仅存在于调试版本中,并且断言如果出现错误,因此在调试中完成的单元测试将会遇到问题.
>树现在通过我的单元测试,虽然它们可以更广泛 – 我写了他们来调试Delphi树的Tomes更简单.此代码不作任何形式的担保或保证.考虑未经测试在使用之前先写测试.请注意,如果你发现一个错误:)

代码

节点修改

我向节点添加了以下帮助方法,以便在阅读时使代码更有文字性.例如,如果Node = Node.Parent.btChild [ctLeft]然后…,则原始代码通常通过测试(盲目转换为Delphi和未修改的ToD结构)来测试节点是否为其父级的左侧子节点,而现在您可以测试如果Node.IsLeft然后…等等.记录定义中的方法原型不包括在内,以节省空间,但应该是明显的:)

  1. function TtdBinTreeNode.Parent: PtdBinTreeNode;
  2. begin
  3. assert(btParent <> nil,'Parent is nil');
  4. Result := btParent;
  5. end;
  6.  
  7. function TtdBinTreeNode.Grandparent: PtdBinTreeNode;
  8. begin
  9. assert(btParent <> nil,'Parent is nil');
  10. Result := btParent.btParent;
  11. assert(Result <> nil,'Grandparent is nil - child of root node?');
  12. end;
  13.  
  14. function TtdBinTreeNode.Sibling: PtdBinTreeNode;
  15. begin
  16. assert(btParent <> nil,'Parent is nil');
  17. if @Self = btParent.btChild[ctLeft] then
  18. Exit(btParent.btChild[ctRight])
  19. else
  20. Exit(btParent.btChild[ctLeft]);
  21. end;
  22.  
  23. function TtdBinTreeNode.Uncle: PtdBinTreeNode;
  24. begin
  25. assert(btParent <> nil,'Parent is nil');
  26. // Can be nil if grandparent has only one child (children of root have no uncle)
  27. Result := btParent.Sibling;
  28. end;
  29.  
  30. function TtdBinTreeNode.LeftChild: PtdBinTreeNode;
  31. begin
  32. Result := btChild[ctLeft];
  33. end;
  34.  
  35. function TtdBinTreeNode.RightChild: PtdBinTreeNode;
  36. begin
  37. Result := btChild[ctRight];
  38. end;
  39.  
  40. function TtdBinTreeNode.IsLeft: Boolean;
  41. begin
  42. Result := @Self = Parent.LeftChild;
  43. end;
  44.  
  45. function TtdBinTreeNode.IsRight: Boolean;
  46. begin
  47. Result := @Self = Parent.RightChild;
  48. end;

我还添加了现有IsRed()等额外的方法来测试它是否为黑色(如果IsBlack(Node)如果不是IsRed(Node)IsBlack(Node)),并且得到颜色,那么IMO代码扫描更好,包括处理一个nil节点请注意,这些需要保持一致 – 例如IsRed对于一个nil节点返回false,所以一个nil节点是黑色的(这也与红黑树的属性和一致的黑色节点数量有关在一条叶子的路上.)

  1. function IsBlack(aNode : PtdBinTreeNode) : boolean;
  2. begin
  3. Result := not IsRed(aNode);
  4. end;
  5.  
  6. function NodeColor(aNode :PtdBinTreeNode) : TtdRBColor;
  7. begin
  8. if aNode = nil then Exit(rbBlack);
  9. Result := aNode.btColor;
  10. end;

红黑限制验证

如上所述,这些方法验证了树的结构和红黑约束,并且是原始C代码中相同方法的直接转换.如果类定义中没有调试,则验证被声明为内联.如果没有调试,该方法应该是空的,希望可以被编译器完全删除.验证在插入和删除方法的开头和结尾调用,以确保修改前后的树是正确的.

  1. procedure TtdRedBlackTree.Verify;
  2. begin
  3. {$ifdef DEBUG}
  4. VerifyNodesRedOrBlack(FBinTree.Root);
  5. VerifyRootIsBlack;
  6. // 3 is implicit
  7. VerifyRedBlackRelationship(FBinTree.Root);
  8. VerifyBlackNodeCount(FBinTree.Root);
  9. {$endif}
  10. end;
  11.  
  12. procedure TtdRedBlackTree.VerifyNodesRedOrBlack(const Node : PtdBinTreeNode);
  13. begin
  14. // Normally implicitly ok in Delphi,due to type system - can't assign something else
  15. // However,node uses a union / case to write to the same value,theoretically
  16. // only for other tree types,so worth checking
  17. assert((Node.btColor = rbRed) or (Node.btColor = rbBlack));
  18. if Node = nil then Exit;
  19. VerifyNodesRedOrBlack(Node.LeftChild);
  20. VerifyNodesRedOrBlack(Node.RightChild);
  21. end;
  22.  
  23. procedure TtdRedBlackTree.VerifyRootIsBlack;
  24. begin
  25. assert(IsBlack(FBinTree.Root));
  26. end;
  27.  
  28. procedure TtdRedBlackTree.VerifyRedBlackRelationship(const Node : PtdBinTreeNode);
  29. begin
  30. // Every red node has two black children; or,the parent of every red node is black.
  31. if IsRed(Node) then begin
  32. assert(IsBlack(Node.LeftChild));
  33. assert(IsBlack(Node.RightChild));
  34. assert(IsBlack(Node.Parent));
  35. end;
  36. if Node = nil then Exit;
  37. VerifyRedBlackRelationship(Node.LeftChild);
  38. VerifyRedBlackRelationship(Node.RightChild);
  39. end;
  40.  
  41. procedure VerifyBlackNodeCountHelper(const Node : PtdBinTreeNode; BlackCount : NativeInt; var PathBlackCount : NativeInt);
  42. begin
  43. if IsBlack(Node) then begin
  44. Inc(BlackCount);
  45. end;
  46.  
  47. if Node = nil then begin
  48. if PathBlackCount = -1 then begin
  49. PathBlackCount := BlackCount;
  50. end else begin
  51. assert(BlackCount = PathBlackCount);
  52. end;
  53. Exit;
  54. end;
  55. VerifyBlackNodeCountHelper(Node.LeftChild,BlackCount,PathBlackCount);
  56. VerifyBlackNodeCountHelper(Node.RightChild,PathBlackCount);
  57. end;
  58.  
  59. procedure TtdRedBlackTree.VerifyBlackNodeCount(const Node : PtdBinTreeNode);
  60. var
  61. PathBlackCount : NativeInt;
  62. begin
  63. // All paths from a node to its leaves contain the same number of black nodes.
  64. PathBlackCount := -1;
  65. VerifyBlackNodeCountHelper(Node,PathBlackCount);
  66. end;

旋转和其他有用的树方法

检查节点是否是根节点的帮助方法,将节点设置为根节点,用另一个节点替换一个节点,执行左右旋转,并按照右侧节点将树跟随到叶片.使这些受保护的红黑树类的成员.

  1. procedure TtdRedBlackTree.RotateLeft(Node: PtdBinTreeNode);
  2. var
  3. R : PtdBinTreeNode;
  4. begin
  5. R := Node.RightChild;
  6. ReplaceNode(Node,R);
  7. Node.btChild[ctRight] := R.LeftChild;
  8. if R.LeftChild <> nil then begin
  9. R.LeftChild.btParent := Node;
  10. end;
  11. R.btChild[ctLeft] := Node;
  12. Node.btParent := R;
  13. end;
  14.  
  15. procedure TtdRedBlackTree.RotateRight(Node: PtdBinTreeNode);
  16. var
  17. L : PtdBinTreeNode;
  18. begin
  19. L := Node.LeftChild;
  20. ReplaceNode(Node,L);
  21. Node.btChild[ctLeft] := L.RightChild;
  22. if L.RightChild <> nil then begin
  23. L.RightChild.btParent := Node;
  24. end;
  25. L.btChild[ctRight] := Node;
  26. Node.btParent := L;
  27. end;
  28.  
  29. procedure TtdRedBlackTree.ReplaceNode(OldNode,NewNode: PtdBinTreeNode);
  30. begin
  31. if IsRoot(OldNode) then begin
  32. SetRoot(NewNode);
  33. end else begin
  34. if OldNode.IsLeft then begin // // Is the left child of its parent
  35. OldNode.Parent.btChild[ctLeft] := NewNode;
  36. end else begin
  37. OldNode.Parent.btChild[ctRight] := NewNode;
  38. end;
  39. end;
  40. if NewNode <> nil then begin
  41. newNode.btParent := OldNode.Parent;
  42. end;
  43. end;
  44.  
  45. function TtdRedBlackTree.IsRoot(const Node: PtdBinTreeNode): Boolean;
  46. begin
  47. Result := Node = FBinTree.Root;
  48. end;
  49.  
  50. procedure TtdRedBlackTree.SetRoot(Node: PtdBinTreeNode);
  51. begin
  52. Node.btColor := rbBlack; // Root is always black
  53. FBinTree.SetRoot(Node);
  54. Node.btParent.btColor := rbBlack; // FHead is black
  55. end;
  56.  
  57. function TtdRedBlackTree.MaximumNode(Node: PtdBinTreeNode): PtdBinTreeNode;
  58. begin
  59. assert(Node <> nil);
  60. while Node.RightChild <> nil do begin
  61. Node := Node.RightChild;
  62. end;
  63. Result := Node;
  64. end;

插入和删除

红黑树是内部树FBITree周围的包装.该代码以太连接的方式直接修改树. FBinTree和包装红黑树都保留了一个计数节点的数量,并使这个更清洁我删除了TtdBinarySearchTree(红黑树的祖先)的FCount并重定向了Count以返回FBinTree.Count,即询问二叉搜索树和红黑树类使用的实际内部树 – 这毕竟是拥有节点的东西.我还添加了NodeInserted和NodeRemoved的通知方法增加和减少计数.代码包括(微不足道).

我还提取了一些分配节点和处理节点的方法 – 不要从树中插入或删除,或者做任何关于节点的连接或存在的事情;这些是为了照顾节点本身的创建和销毁.请注意,节点创建需要将节点的颜色设置为红色 – 此点之后的颜色更改被照看.这也确保了节点被释放时,有机会释放与之相关联的数据.

  1. function TtdBinaryTree.NewNode(const Item : Pointer): PtdBinTreeNode;
  2. begin
  3. {allocate a new node }
  4. Result := BTNodeManager.AllocNode;
  5. Result^.btParent := nil;
  6. Result^.btChild[ctLeft] := nil;
  7. Result^.btChild[ctRight] := nil;
  8. Result^.btData := Item;
  9. Result.btColor := rbRed; // Red initially
  10. end;
  11.  
  12. procedure TtdBinaryTree.DisposeNode(Node: PtdBinTreeNode);
  13. begin
  14. // Free whatever Data was pointing to,if necessary
  15. if Assigned(FDispose) then FDispose(Node.btData);
  16. // Free the node
  17. BTNodeManager.FreeNode(Node);
  18. // Decrement the node count
  19. NodeRemoved;
  20. end;

使用这些额外的方法,使用以下代码进行插入和删除.代码评论,但是我建议您阅读original page以及德尔福的Tomes书籍,了解旋转的解释以及代码测试的各种情况.

插入

  1. procedure TtdRedBlackTree.Insert(aItem : pointer);
  2. var
  3. NewNode,Node : PtdBinTreeNode;
  4. Comparison : NativeInt;
  5. begin
  6. Verify;
  7. newNode := FBinTree.NewNode(aItem);
  8. assert(IsRed(NewNode)); // new node is red
  9. if IsRoot(nil) then begin
  10. SetRoot(NewNode);
  11. NodeInserted;
  12. end else begin
  13. Node := FBinTree.Root;
  14. while True do begin
  15. Comparison := FCompare(aItem,Node.btData);
  16. case Comparison of
  17. 0: begin
  18. // Equal: tree doesn't support duplicate values
  19. assert(false,'Should not insert a duplicate item');
  20. FBinTree.DisposeNode(NewNode);
  21. Exit;
  22. end;
  23. -1: begin
  24. if Node.LeftChild = nil then begin
  25. Node.btChild[ctLeft] := NewNode;
  26. Break;
  27. end else begin
  28. Node := Node.LeftChild;
  29. end;
  30. end;
  31. else begin
  32. assert(Comparison = 1,'Only -1,0 and 1 are valid comparison values');
  33. if Node.RightChild = nil then begin
  34. Node.btChild[ctRight] := NewNode;
  35. Break;
  36. end else begin
  37. Node := Node.RightChild;
  38. end;
  39. end;
  40. end;
  41. end;
  42. NewNode.btParent := Node; // Because assigned to left or right child above
  43. NodeInserted; // Increment count
  44. end;
  45. InsertCase1(NewNode);
  46. Verify;
  47. end;
  48.  
  49. // Node is now the root of the tree. Node must be black; because it's the only
  50. // node,there is only one path,so the number of black nodes is ok
  51. procedure TtdRedBlackTree.InsertCase1(Node: PtdBinTreeNode);
  52. begin
  53. if not IsRoot(Node) then begin
  54. InsertCase2(Node);
  55. end else begin
  56. // Node is root (the less likely case)
  57. Node.btColor := rbBlack;
  58. end;
  59. end;
  60.  
  61. // New node has a black parent: all properties ok
  62. procedure TtdRedBlackTree.InsertCase2(Node: PtdBinTreeNode);
  63. begin
  64. // If it is black,then everything ok,do nothing
  65. if not IsBlack(Node.Parent) then InsertCase3(Node);
  66. end;
  67.  
  68. // More complex: uncle is red. Recolor parent and uncle black and grandparent red
  69. // The grandparent change may break the red-black properties,so start again
  70. // from case 1.
  71. procedure TtdRedBlackTree.InsertCase3(Node: PtdBinTreeNode);
  72. begin
  73. if IsRed(Node.Uncle) then begin
  74. Node.Parent.btColor := rbBlack;
  75. Node.Uncle.btColor := rbBlack;
  76. Node.Grandparent.btColor := rbRed;
  77. InsertCase1(Node.Grandparent);
  78. end else begin
  79. InsertCase4(Node);
  80. end;
  81. end;
  82.  
  83. // "In this case,we deal with two cases that are mirror images of one another:
  84. // - The new node is the right child of its parent and the parent is the left child
  85. // of the grandparent. In this case we rotate left about the parent.
  86. // - The new node is the left child of its parent and the parent is the right child
  87. // of the grandparent. In this case we rotate right about the parent.
  88. // Neither of these fixes the properties,but they put the tree in the correct form
  89. // to apply case 5."
  90. procedure TtdRedBlackTree.InsertCase4(Node: PtdBinTreeNode);
  91. begin
  92. if (Node.IsRight) and (Node.Parent = Node.Grandparent.LeftChild) then begin
  93. RotateLeft(Node.Parent);
  94. Node := Node.LeftChild;
  95. end else if (Node.IsLeft) and (Node.Parent = Node.Grandparent.RightChild) then begin
  96. RotateRight(Node.Parent);
  97. Node := Node.RightChild;
  98. end;
  99. InsertCase5(Node);
  100. end;
  101.  
  102. // " In this final case,we deal with two cases that are mirror images of one another:
  103. // - The new node is the left child of its parent and the parent is the left child
  104. // of the grandparent. In this case we rotate right about the grandparent.
  105. // - The new node is the right child of its parent and the parent is the right child
  106. // of the grandparent. In this case we rotate left about the grandparent.
  107. // Now the properties are satisfied and all cases have been covered."
  108. procedure TtdRedBlackTree.InsertCase5(Node: PtdBinTreeNode);
  109. begin
  110. Node.Parent.btColor := rbBlack;
  111. Node.Grandparent.btColor := rbRed;
  112. if (Node.IsLeft) and (Node.Parent = Node.Grandparent.LeftChild) then begin
  113. RotateRight(Node.Grandparent);
  114. end else begin
  115. assert((Node.IsRight) and (Node.Parent = Node.Grandparent.RightChild));
  116. RotateLeft(Node.Grandparent);
  117. end;
  118. end;

删除

  1. procedure TtdRedBlackTree.Delete(aItem : pointer);
  2. var
  3. Node,Predecessor,Child : PtdBinTreeNode;
  4. begin
  5. Node := bstFindNodeToDelete(aItem);
  6. if Node = nil then begin
  7. assert(false,'Node not found');
  8. Exit;
  9. end;
  10. if (Node.LeftChild <> nil) and (Node.RightChild <> nil) then begin
  11. Predecessor := MaximumNode(Node.LeftChild);
  12. Node.btData := aItem;
  13. Node := Predecessor;
  14. end;
  15.  
  16. assert((Node.LeftChild = nil) or (Node.RightChild = nil));
  17. if Node.LeftChild = nil then
  18. Child := Node.RightChild
  19. else
  20. Child := Node.LeftChild;
  21.  
  22. if IsBlack(Node) then begin
  23. Node.btColor := NodeColor(Child);
  24. DeleteCase1(Node);
  25. end;
  26. ReplaceNode(Node,Child);
  27. if IsRoot(Node) and (Child <> nil) then begin
  28. Child.btColor := rbBlack;
  29. end;
  30.  
  31. FBinTree.DisposeNode(Node);
  32.  
  33. Verify;
  34. end;
  35.  
  36. // If Node is the root node,the deletion removes one black node from every path
  37. // No properties violated,return
  38. procedure TtdRedBlackTree.DeleteCase1(Node: PtdBinTreeNode);
  39. begin
  40. if IsRoot(Node) then Exit;
  41. DeleteCase2(Node);
  42. end;
  43.  
  44. // Node has a red sibling; swap colors,and rotate so the sibling is the parent
  45. // of its former parent. Continue to one of the next cases
  46. procedure TtdRedBlackTree.DeleteCase2(Node: PtdBinTreeNode);
  47. begin
  48. if IsRed(Node.Sibling) then begin
  49. Node.Parent.btColor := rbRed;
  50. Node.Sibling.btColor := rbBlack;
  51. if Node.IsLeft then begin
  52. RotateLeft(Node.Parent);
  53. end else begin
  54. RotateRight(Node.Parent);
  55. end;
  56. end;
  57. DeleteCase3(Node);
  58. end;
  59.  
  60. // Node's parent,sibling and sibling's children are black; paint the sibling red.
  61. // All paths through Node now have one less black node,so recursively run case 1
  62. procedure TtdRedBlackTree.DeleteCase3(Node: PtdBinTreeNode);
  63. begin
  64. if IsBlack(Node.Parent) and
  65. IsBlack(Node.Sibling) and
  66. IsBlack(Node.Sibling.LeftChild) and
  67. IsBlack(Node.Sibling.RightChild) then
  68. begin
  69. Node.Sibling.btColor := rbRed;
  70. DeleteCase1(Node.Parent);
  71. end else begin
  72. DeleteCase4(Node);
  73. end;
  74. end;
  75.  
  76. // Node's sibling and sibling's children are black,but node's parent is red.
  77. // Swap colors of sibling and parent Node; restores the tree properties
  78. procedure TtdRedBlackTree.DeleteCase4(Node: PtdBinTreeNode);
  79. begin
  80. if IsRed(Node.Parent) and
  81. IsBlack(Node.Sibling) and
  82. IsBlack(Node.Sibling.LeftChild) and
  83. IsBlack(Node.Sibling.RightChild) then
  84. begin
  85. Node.Sibling.btColor := rbRed;
  86. Node.Parent.btColor := rbBlack;
  87. end else begin
  88. DeleteCase5(Node);
  89. end;
  90. end;
  91.  
  92. // Mirror image cases: Node's sibling is black,sibling's left child is red,// sibling's right child is black,and Node is the left child. Swap the colors
  93. // of sibling and its left sibling and rotate right at S
  94. // And vice versa: Node's sibling is black,sibling's right child is red,sibling's
  95. // left child is black,and Node is the right child of its parent. Swap the colors
  96. // of sibling and its right sibling and rotate left at the sibling.
  97. procedure TtdRedBlackTree.DeleteCase5(Node: PtdBinTreeNode);
  98. begin
  99. if Node.IsLeft and
  100. IsBlack(Node.Sibling) and
  101. IsRed(Node.Sibling.LeftChild) and
  102. IsBlack(Node.Sibling.RightChild) then
  103. begin
  104. Node.Sibling.btColor := rbRed;
  105. Node.Sibling.LeftChild.btColor := rbBlack;
  106. RotateRight(Node.Sibling);
  107. end else if Node.IsRight and
  108. IsBlack(Node.Sibling) and
  109. IsRed(Node.Sibling.RightChild) and
  110. IsBlack(Node.Sibling.LeftChild) then
  111. begin
  112. Node.Sibling.btColor := rbRed;
  113. Node.Sibling.RightChild.btColor := rbBlack;
  114. RotateLeft(Node.Sibling);
  115. end;
  116. DeleteCase6(Node);
  117. end;
  118.  
  119. // Mirror image cases:
  120. // - "N's sibling S is black,S's right child is red,and N is the left child of its
  121. // parent. We exchange the colors of N's parent and sibling,make S's right child
  122. // black,then rotate left at N's parent.
  123. // - N's sibling S is black,S's left child is red,and N is the right child of its
  124. // parent. We exchange the colors of N's parent and sibling,make S's left child
  125. // black,then rotate right at N's parent.
  126. // This accomplishes three things at once:
  127. // - We add a black node to all paths through N,either by adding a black S to those
  128. // paths or by recoloring N's parent black.
  129. // - We remove a black node from all paths through S's red child,either by removing
  130. // P from those paths or by recoloring S.
  131. // - We recolor S's red child black,adding a black node back to all paths through
  132. // S's red child.
  133. // S's left child has become a child of N's parent during the rotation and so is
  134. // unaffected."
  135. procedure TtdRedBlackTree.DeleteCase6(Node: PtdBinTreeNode);
  136. begin
  137. Node.Sibling.btColor := NodeColor(Node.Parent);
  138. Node.Parent.btColor := rbBlack;
  139. if Node.IsLeft then begin
  140. assert(IsRed(Node.Sibling.RightChild));
  141. Node.Sibling.RightChild.btColor := rbBlack;
  142. RotateLeft(Node.Parent);
  143. end else begin
  144. assert(IsRed(Node.Sibling.LeftChild));
  145. Node.Sibling.LeftChild.btColor := rbBlack;
  146. RotateRight(Node.Parent);
  147. end;
  148. end;

最后的笔记

>我希望这是有用的!如果你发现它很有用,请留言说你如何使用它.我很想知道.>它不附带任何保证或保证.它通过我的单元测试,但它们可能更全面 – 我所能说的是,这个代码成功地在Delphi代码的Tomes失败了.谁知道是否以其他方式失败使用您自己的风险.我建议你为它编写测试.如果你发现错误,请在这里评论!有乐趣:)

猜你在找的Delphi相关文章