Mirror of Svelto.ECS because we're a fan of it
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

LeftLeaningKeyedRedBlackTree.cs 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. // Uncomment this to enable the following debugging aids:
  2. // LeftLeaningRedBlackTree.HtmlFragment
  3. // LeftLeaningRedBlackTree.Node.HtmlFragment
  4. // LeftLeaningRedBlackTree.AssertInvariants
  5. // #define DEBUGGING
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. /// <summary>
  10. /// Implements a left-leaning red-black tree.
  11. /// </summary>
  12. /// <remarks>
  13. /// Based on the research paper "Left-leaning Red-Black Trees"
  14. /// by Robert Sedgewick. More information available at:
  15. /// http://www.cs.princeton.edu/~rs/talks/LLRB/RedBlack.pdf
  16. /// http://www.cs.princeton.edu/~rs/talks/LLRB/08Penn.pdf
  17. /// </remarks>
  18. /// <typeparam name="TKey">Type of keys.</typeparam>
  19. public class LeftLeaningKeyedRedBlackTree<TKey> where TKey: IComparable<TKey>
  20. {
  21. /// <summary>
  22. /// Stores the root node of the tree.
  23. /// </summary>
  24. private Node _rootNode;
  25. /// <summary>
  26. /// Represents a node of the tree.
  27. /// </summary>
  28. /// <remarks>
  29. /// Using fields instead of properties drops execution time by about 40%.
  30. /// </remarks>
  31. [DebuggerDisplay("Key={Key}")]
  32. private class Node
  33. {
  34. /// <summary>
  35. /// Gets or sets the node's key.
  36. /// </summary>
  37. public TKey Key;
  38. /// <summary>
  39. /// Gets or sets the left node.
  40. /// </summary>
  41. public Node Left;
  42. /// <summary>
  43. /// Gets or sets the right node.
  44. /// </summary>
  45. public Node Right;
  46. /// <summary>
  47. /// Gets or sets the color of the node.
  48. /// </summary>
  49. public bool IsBlack;
  50. #if DEBUGGING
  51. /// <summary>
  52. /// Gets an HTML fragment representing the node and its children.
  53. /// </summary>
  54. public string HtmlFragment
  55. {
  56. get
  57. {
  58. return
  59. "<table border='1'>" +
  60. "<tr>" +
  61. "<td colspan='2' align='center' bgcolor='" + (IsBlack ? "gray" : "red") + "'>" + Key + ", " + Value + " [" + Siblings + "]</td>" +
  62. "</tr>" +
  63. "<tr>" +
  64. "<td valign='top'>" + (null != Left ? Left.HtmlFragment : "[null]") + "</td>" +
  65. "<td valign='top'>" + (null != Right ? Right.HtmlFragment : "[null]") + "</td>" +
  66. "</tr>" +
  67. "</table>";
  68. }
  69. }
  70. #endif
  71. }
  72. /// <summary>
  73. /// Adds a key/value pair to the tree.
  74. /// </summary>
  75. /// <param name="key">Key to add.</param>
  76. public void Add(TKey key)
  77. {
  78. _rootNode = Add(_rootNode, key);
  79. _rootNode.IsBlack = true;
  80. #if DEBUGGING
  81. AssertInvariants();
  82. #endif
  83. }
  84. /// <summary>
  85. /// Removes a key/value pair from the tree.
  86. /// </summary>
  87. /// <param name="key">Key to remove.</param>
  88. /// <returns>True if key/value present and removed.</returns>
  89. public bool Remove(TKey key)
  90. {
  91. int initialCount = Count;
  92. if (null != _rootNode)
  93. {
  94. _rootNode = Remove(_rootNode, key);
  95. if (null != _rootNode)
  96. {
  97. _rootNode.IsBlack = true;
  98. }
  99. }
  100. #if DEBUGGING
  101. AssertInvariants();
  102. #endif
  103. return initialCount != Count;
  104. }
  105. /// <summary>
  106. /// Removes all nodes in the tree.
  107. /// </summary>
  108. public void Clear()
  109. {
  110. _rootNode = null;
  111. Count = 0;
  112. #if DEBUGGING
  113. AssertInvariants();
  114. #endif
  115. }
  116. /// <summary>
  117. /// Gets a sorted list of keys in the tree.
  118. /// </summary>
  119. /// <returns>Sorted list of keys.</returns>
  120. public IEnumerable<TKey> GetKeys()
  121. {
  122. TKey lastKey = default(TKey);
  123. bool lastKeyValid = false;
  124. return Traverse(
  125. _rootNode,
  126. n => !lastKeyValid || !object.Equals(lastKey, n.Key),
  127. n =>
  128. {
  129. lastKey = n.Key;
  130. lastKeyValid = true;
  131. return lastKey;
  132. });
  133. }
  134. /// <summary>
  135. /// Gets the count of key/value pairs in the tree.
  136. /// </summary>
  137. public int Count { get; private set; }
  138. /// <summary>
  139. /// Gets the minimum key in the tree.
  140. /// </summary>
  141. public TKey MinimumKey
  142. {
  143. get { return GetExtreme(_rootNode, n => n.Left, n => n.Key); }
  144. }
  145. /// <summary>
  146. /// Gets the maximum key in the tree.
  147. /// </summary>
  148. public TKey MaximumKey
  149. {
  150. get { return GetExtreme(_rootNode, n => n.Right, n => n.Key); }
  151. }
  152. /// <summary>
  153. /// Returns true if the specified node is red.
  154. /// </summary>
  155. /// <param name="node">Specified node.</param>
  156. /// <returns>True if specified node is red.</returns>
  157. private static bool IsRed(Node node)
  158. {
  159. if (null == node)
  160. {
  161. // "Virtual" leaf nodes are always black
  162. return false;
  163. }
  164. return !node.IsBlack;
  165. }
  166. /// <summary>
  167. /// Adds the specified key/value pair below the specified root node.
  168. /// </summary>
  169. /// <param name="node">Specified node.</param>
  170. /// <param name="key">Key to add.</param>
  171. /// <param name="value">Value to add.</param>
  172. /// <returns>New root node.</returns>
  173. private Node Add(Node node, TKey key)
  174. {
  175. if (null == node)
  176. {
  177. // Insert new node
  178. Count++;
  179. return new Node { Key = key };
  180. }
  181. if (IsRed(node.Left) && IsRed(node.Right))
  182. {
  183. // Split node with two red children
  184. FlipColor(node);
  185. }
  186. // Find right place for new node
  187. int comparisonResult = KeyComparison(key, node.Key);
  188. if (comparisonResult < 0)
  189. {
  190. node.Left = Add(node.Left, key);
  191. }
  192. else if (0 < comparisonResult)
  193. {
  194. node.Right = Add(node.Right, key);
  195. }
  196. if (IsRed(node.Right))
  197. {
  198. // Rotate to prevent red node on right
  199. node = RotateLeft(node);
  200. }
  201. if (IsRed(node.Left) && IsRed(node.Left.Left))
  202. {
  203. // Rotate to prevent consecutive red nodes
  204. node = RotateRight(node);
  205. }
  206. return node;
  207. }
  208. /// <summary>
  209. /// Removes the specified key/value pair from below the specified node.
  210. /// </summary>
  211. /// <param name="node">Specified node.</param>
  212. /// <param name="key">Key to remove.</param>
  213. /// <returns>True if key/value present and removed.</returns>
  214. private Node Remove(Node node, TKey key)
  215. {
  216. int comparisonResult = KeyComparison(key, node.Key);
  217. if (comparisonResult < 0)
  218. {
  219. // * Continue search if left is present
  220. if (null != node.Left)
  221. {
  222. if (!IsRed(node.Left) && !IsRed(node.Left.Left))
  223. {
  224. // Move a red node over
  225. node = MoveRedLeft(node);
  226. }
  227. // Remove from left
  228. node.Left = Remove(node.Left, key);
  229. }
  230. }
  231. else
  232. {
  233. if (IsRed(node.Left))
  234. {
  235. // Flip a 3 node or unbalance a 4 node
  236. node = RotateRight(node);
  237. }
  238. if ((0 == KeyComparison(key, node.Key)) && (null == node.Right))
  239. {
  240. // Remove leaf node
  241. Debug.Assert(null == node.Left, "About to remove an extra node.");
  242. Count--;
  243. // Leaf node is gone
  244. return null;
  245. }
  246. // * Continue search if right is present
  247. if (null != node.Right)
  248. {
  249. if (!IsRed(node.Right) && !IsRed(node.Right.Left))
  250. {
  251. // Move a red node over
  252. node = MoveRedRight(node);
  253. }
  254. if (0 == KeyComparison(key, node.Key))
  255. {
  256. // Remove leaf node
  257. Count--;
  258. // Find the smallest node on the right, swap, and remove it
  259. Node m = GetExtreme(node.Right, n => n.Left, n => n);
  260. node.Key = m.Key;
  261. node.Right = DeleteMinimum(node.Right);
  262. }
  263. else
  264. {
  265. // Remove from right
  266. node.Right = Remove(node.Right, key);
  267. }
  268. }
  269. }
  270. // Maintain invariants
  271. return FixUp(node);
  272. }
  273. /// <summary>
  274. /// Flip the colors of the specified node and its direct children.
  275. /// </summary>
  276. /// <param name="node">Specified node.</param>
  277. private static void FlipColor(Node node)
  278. {
  279. node.IsBlack = !node.IsBlack;
  280. node.Left.IsBlack = !node.Left.IsBlack;
  281. node.Right.IsBlack = !node.Right.IsBlack;
  282. }
  283. /// <summary>
  284. /// Rotate the specified node "left".
  285. /// </summary>
  286. /// <param name="node">Specified node.</param>
  287. /// <returns>New root node.</returns>
  288. private static Node RotateLeft(Node node)
  289. {
  290. Node x = node.Right;
  291. node.Right = x.Left;
  292. x.Left = node;
  293. x.IsBlack = node.IsBlack;
  294. node.IsBlack = false;
  295. return x;
  296. }
  297. /// <summary>
  298. /// Rotate the specified node "right".
  299. /// </summary>
  300. /// <param name="node">Specified node.</param>
  301. /// <returns>New root node.</returns>
  302. private static Node RotateRight(Node node)
  303. {
  304. Node x = node.Left;
  305. node.Left = x.Right;
  306. x.Right = node;
  307. x.IsBlack = node.IsBlack;
  308. node.IsBlack = false;
  309. return x;
  310. }
  311. /// <summary>
  312. /// Moves a red node from the right child to the left child.
  313. /// </summary>
  314. /// <param name="node">Parent node.</param>
  315. /// <returns>New root node.</returns>
  316. private static Node MoveRedLeft(Node node)
  317. {
  318. FlipColor(node);
  319. if (IsRed(node.Right.Left))
  320. {
  321. node.Right = RotateRight(node.Right);
  322. node = RotateLeft(node);
  323. FlipColor(node);
  324. // * Avoid creating right-leaning nodes
  325. if (IsRed(node.Right.Right))
  326. {
  327. node.Right = RotateLeft(node.Right);
  328. }
  329. }
  330. return node;
  331. }
  332. /// <summary>
  333. /// Moves a red node from the left child to the right child.
  334. /// </summary>
  335. /// <param name="node">Parent node.</param>
  336. /// <returns>New root node.</returns>
  337. private static Node MoveRedRight(Node node)
  338. {
  339. FlipColor(node);
  340. if (IsRed(node.Left.Left))
  341. {
  342. node = RotateRight(node);
  343. FlipColor(node);
  344. }
  345. return node;
  346. }
  347. /// <summary>
  348. /// Deletes the minimum node under the specified node.
  349. /// </summary>
  350. /// <param name="node">Specified node.</param>
  351. /// <returns>New root node.</returns>
  352. private Node DeleteMinimum(Node node)
  353. {
  354. if (null == node.Left)
  355. {
  356. // Nothing to do
  357. return null;
  358. }
  359. if (!IsRed(node.Left) && !IsRed(node.Left.Left))
  360. {
  361. // Move red node left
  362. node = MoveRedLeft(node);
  363. }
  364. // Recursively delete
  365. node.Left = DeleteMinimum(node.Left);
  366. // Maintain invariants
  367. return FixUp(node);
  368. }
  369. /// <summary>
  370. /// Maintains invariants by adjusting the specified nodes children.
  371. /// </summary>
  372. /// <param name="node">Specified node.</param>
  373. /// <returns>New root node.</returns>
  374. private static Node FixUp(Node node)
  375. {
  376. if (IsRed(node.Right))
  377. {
  378. // Avoid right-leaning node
  379. node = RotateLeft(node);
  380. }
  381. if (IsRed(node.Left) && IsRed(node.Left.Left))
  382. {
  383. // Balance 4-node
  384. node = RotateRight(node);
  385. }
  386. if (IsRed(node.Left) && IsRed(node.Right))
  387. {
  388. // Push red up
  389. FlipColor(node);
  390. }
  391. // * Avoid leaving behind right-leaning nodes
  392. if ((null != node.Left) && IsRed(node.Left.Right) && !IsRed(node.Left.Left))
  393. {
  394. node.Left = RotateLeft(node.Left);
  395. if (IsRed(node.Left))
  396. {
  397. // Balance 4-node
  398. node = RotateRight(node);
  399. }
  400. }
  401. return node;
  402. }
  403. /// <summary>
  404. /// Gets the (first) node corresponding to the specified key.
  405. /// </summary>
  406. /// <param name="key">Key to search for.</param>
  407. /// <returns>Corresponding node or null if none found.</returns>
  408. private Node GetNodeForKey(TKey key)
  409. {
  410. // Initialize
  411. Node node = _rootNode;
  412. while (null != node)
  413. {
  414. // Compare keys and go left/right
  415. int comparisonResult = key.CompareTo(node.Key);
  416. if (comparisonResult < 0)
  417. {
  418. node = node.Left;
  419. }
  420. else if (0 < comparisonResult)
  421. {
  422. node = node.Right;
  423. }
  424. else
  425. {
  426. // Match; return node
  427. return node;
  428. }
  429. }
  430. // No match found
  431. return null;
  432. }
  433. /// <summary>
  434. /// Gets an extreme (ex: minimum/maximum) value.
  435. /// </summary>
  436. /// <typeparam name="T">Type of value.</typeparam>
  437. /// <param name="node">Node to start from.</param>
  438. /// <param name="successor">Successor function.</param>
  439. /// <param name="selector">Selector function.</param>
  440. /// <returns>Extreme value.</returns>
  441. private static T GetExtreme<T>(Node node, Func<Node, Node> successor, Func<Node, T> selector)
  442. {
  443. // Initialize
  444. T extreme = default(T);
  445. Node current = node;
  446. while (null != current)
  447. {
  448. // Go to extreme
  449. extreme = selector(current);
  450. current = successor(current);
  451. }
  452. return extreme;
  453. }
  454. /// <summary>
  455. /// Traverses a subset of the sequence of nodes in order and selects the specified nodes.
  456. /// </summary>
  457. /// <typeparam name="T">Type of elements.</typeparam>
  458. /// <param name="node">Starting node.</param>
  459. /// <param name="condition">Condition method.</param>
  460. /// <param name="selector">Selector method.</param>
  461. /// <returns>Sequence of selected nodes.</returns>
  462. private IEnumerable<T> Traverse<T>(Node node, Func<Node, bool> condition, Func<Node, T> selector)
  463. {
  464. // Create a stack to avoid recursion
  465. Stack<Node> stack = new Stack<Node>();
  466. Node current = node;
  467. while (null != current)
  468. {
  469. if (null != current.Left)
  470. {
  471. // Save current state and go left
  472. stack.Push(current);
  473. current = current.Left;
  474. }
  475. else
  476. {
  477. do
  478. {
  479. // Select current node if relevant
  480. if (condition(current))
  481. {
  482. yield return selector(current);
  483. }
  484. // Go right - or up if nothing to the right
  485. current = current.Right;
  486. }
  487. while ((null == current) &&
  488. (0 < stack.Count) &&
  489. (null != (current = stack.Pop())));
  490. }
  491. }
  492. }
  493. /// <summary>
  494. /// Compares the specified keys (primary) and values (secondary).
  495. /// </summary>
  496. /// <param name="leftKey">The left key.</param>
  497. /// <param name="rightKey">The right key.</param>
  498. /// <returns>CompareTo-style results: -1 if left is less, 0 if equal, and 1 if greater than right.</returns>
  499. private int KeyComparison(TKey leftKey, TKey rightKey)
  500. {
  501. return leftKey.CompareTo(rightKey);
  502. }
  503. #if DEBUGGING
  504. /// <summary>
  505. /// Asserts that tree invariants are not violated.
  506. /// </summary>
  507. private void AssertInvariants()
  508. {
  509. // Root is black
  510. Debug.Assert((null == _rootNode) || _rootNode.IsBlack, "Root is not black");
  511. // Every path contains the same number of black nodes
  512. Dictionary<Node, Node> parents = new Dictionary<LeftLeaningRedBlackTree<TKey, TValue>.Node, LeftLeaningRedBlackTree<TKey, TValue>.Node>();
  513. foreach (Node node in Traverse(_rootNode, n => true, n => n))
  514. {
  515. if (null != node.Left)
  516. {
  517. parents[node.Left] = node;
  518. }
  519. if (null != node.Right)
  520. {
  521. parents[node.Right] = node;
  522. }
  523. }
  524. if (null != _rootNode)
  525. {
  526. parents[_rootNode] = null;
  527. }
  528. int treeCount = -1;
  529. foreach (Node node in Traverse(_rootNode, n => (null == n.Left) || (null == n.Right), n => n))
  530. {
  531. int pathCount = 0;
  532. Node current = node;
  533. while (null != current)
  534. {
  535. if (current.IsBlack)
  536. {
  537. pathCount++;
  538. }
  539. current = parents[current];
  540. }
  541. Debug.Assert((-1 == treeCount) || (pathCount == treeCount), "Not all paths have the same number of black nodes.");
  542. treeCount = pathCount;
  543. }
  544. // Verify node properties...
  545. foreach (Node node in Traverse(_rootNode, n => true, n => n))
  546. {
  547. // Left node is less
  548. if (null != node.Left)
  549. {
  550. Debug.Assert(0 > KeyAndValueComparison(node.Left.Key, node.Left.Value, node.Key, node.Value), "Left node is greater than its parent.");
  551. }
  552. // Right node is greater
  553. if (null != node.Right)
  554. {
  555. Debug.Assert(0 < KeyAndValueComparison(node.Right.Key, node.Right.Value, node.Key, node.Value), "Right node is less than its parent.");
  556. }
  557. // Both children of a red node are black
  558. Debug.Assert(!IsRed(node) || (!IsRed(node.Left) && !IsRed(node.Right)), "Red node has a red child.");
  559. // Always left-leaning
  560. Debug.Assert(!IsRed(node.Right) || IsRed(node.Left), "Node is not left-leaning.");
  561. // No consecutive reds (subset of previous rule)
  562. //Debug.Assert(!(IsRed(node) && IsRed(node.Left)));
  563. }
  564. }
  565. /// <summary>
  566. /// Gets an HTML fragment representing the tree.
  567. /// </summary>
  568. public string HtmlDocument
  569. {
  570. get
  571. {
  572. return
  573. "<html>" +
  574. "<body>" +
  575. (null != _rootNode ? _rootNode.HtmlFragment : "[null]") +
  576. "</body>" +
  577. "</html>";
  578. }
  579. }
  580. #endif
  581. }