TreeDictionary.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Diagnostics.CodeAnalysis;
  5. namespace Ryujinx.Common.Collections
  6. {
  7. /// <summary>
  8. /// Dictionary that provides the ability for O(logN) Lookups for keys that exist in the Dictionary, and O(logN) lookups for keys immediately greater than or less than a specified key.
  9. /// </summary>
  10. /// <typeparam name="K">Key</typeparam>
  11. /// <typeparam name="V">Value</typeparam>
  12. public class TreeDictionary<K, V> : IDictionary<K, V> where K : IComparable<K>
  13. {
  14. private const bool Black = true;
  15. private const bool Red = false;
  16. private Node<K, V> _root = null;
  17. private int _count = 0;
  18. public TreeDictionary() { }
  19. #region Public Methods
  20. /// <summary>
  21. /// Returns the value of the node whose key is <paramref name="key"/>, or the default value if no such node exists.
  22. /// </summary>
  23. /// <param name="key">Key of the node value to get</param>
  24. /// <returns>Value associated w/ <paramref name="key"/></returns>
  25. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  26. public V Get(K key)
  27. {
  28. if (key == null)
  29. {
  30. throw new ArgumentNullException(nameof(key));
  31. }
  32. Node<K, V> node = GetNode(key);
  33. if (node == null)
  34. {
  35. return default;
  36. }
  37. return node.Value;
  38. }
  39. /// <summary>
  40. /// Adds a new node into the tree whose key is <paramref name="key"/> key and value is <paramref name="value"/>.
  41. /// <br></br>
  42. /// <b>Note:</b> Adding the same key multiple times will cause the value for that key to be overwritten.
  43. /// </summary>
  44. /// <param name="key">Key of the node to add</param>
  45. /// <param name="value">Value of the node to add</param>
  46. /// <exception cref="ArgumentNullException"><paramref name="key"/> or <paramref name="value"/> are null</exception>
  47. public void Add(K key, V value)
  48. {
  49. if (key == null)
  50. {
  51. throw new ArgumentNullException(nameof(key));
  52. }
  53. if (null == value)
  54. {
  55. throw new ArgumentNullException(nameof(value));
  56. }
  57. Insert(key, value);
  58. }
  59. /// <summary>
  60. /// Removes the node whose key is <paramref name="key"/> from the tree.
  61. /// </summary>
  62. /// <param name="key">Key of the node to remove</param>
  63. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  64. public void Remove(K key)
  65. {
  66. if (key == null)
  67. {
  68. throw new ArgumentNullException(nameof(key));
  69. }
  70. if (Delete(key) != null)
  71. {
  72. _count--;
  73. }
  74. }
  75. /// <summary>
  76. /// Returns the value whose key is equal to or immediately less than <paramref name="key"/>.
  77. /// </summary>
  78. /// <param name="key">Key for which to find the floor value of</param>
  79. /// <returns>Key of node immediately less than <paramref name="key"/></returns>
  80. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  81. public K Floor(K key)
  82. {
  83. Node<K, V> node = FloorNode(key);
  84. if (node != null)
  85. {
  86. return node.Key;
  87. }
  88. return default;
  89. }
  90. /// <summary>
  91. /// Returns the node whose key is equal to or immediately greater than <paramref name="key"/>.
  92. /// </summary>
  93. /// <param name="key">Key for which to find the ceiling node of</param>
  94. /// <returns>Key of node immediately greater than <paramref name="key"/></returns>
  95. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  96. public K Ceiling(K key)
  97. {
  98. Node<K, V> node = CeilingNode(key);
  99. if (node != null)
  100. {
  101. return node.Key;
  102. }
  103. return default;
  104. }
  105. /// <summary>
  106. /// Finds the value whose key is immediately greater than <paramref name="key"/>.
  107. /// </summary>
  108. /// <param name="key">Key to find the successor of</param>
  109. /// <returns>Value</returns>
  110. public K SuccessorOf(K key)
  111. {
  112. Node<K, V> node = GetNode(key);
  113. if (node != null)
  114. {
  115. Node<K, V> successor = SuccessorOf(node);
  116. return successor != null ? successor.Key : default;
  117. }
  118. return default;
  119. }
  120. /// <summary>
  121. /// Finds the value whose key is immediately less than <paramref name="key"/>.
  122. /// </summary>
  123. /// <param name="key">Key to find the predecessor of</param>
  124. /// <returns>Value</returns>
  125. public K PredecessorOf(K key)
  126. {
  127. Node<K, V> node = GetNode(key);
  128. if (node != null)
  129. {
  130. Node<K, V> predecessor = PredecessorOf(node);
  131. return predecessor != null ? predecessor.Key : default;
  132. }
  133. return default;
  134. }
  135. /// <summary>
  136. /// Adds all the nodes in the dictionary as key/value pairs into <paramref name="list"/>.
  137. /// <br></br>
  138. /// The key/value pairs will be added in Level Order.
  139. /// </summary>
  140. /// <param name="list">List to add the tree pairs into</param>
  141. public List<KeyValuePair<K, V>> AsLevelOrderList()
  142. {
  143. List<KeyValuePair<K, V>> list = new List<KeyValuePair<K, V>>();
  144. Queue<Node<K, V>> nodes = new Queue<Node<K, V>>();
  145. if (this._root != null)
  146. {
  147. nodes.Enqueue(this._root);
  148. }
  149. while (nodes.Count > 0)
  150. {
  151. Node<K, V> node = nodes.Dequeue();
  152. list.Add(new KeyValuePair<K, V>(node.Key, node.Value));
  153. if (node.Left != null)
  154. {
  155. nodes.Enqueue(node.Left);
  156. }
  157. if (node.Right != null)
  158. {
  159. nodes.Enqueue(node.Right);
  160. }
  161. }
  162. return list;
  163. }
  164. /// <summary>
  165. /// Adds all the nodes in the dictionary into <paramref name="list"/>.
  166. /// </summary>
  167. /// <returns>A list of all KeyValuePairs sorted by Key Order</returns>
  168. public List<KeyValuePair<K, V>> AsList()
  169. {
  170. List<KeyValuePair<K, V>> list = new List<KeyValuePair<K, V>>();
  171. AddToList(_root, list);
  172. return list;
  173. }
  174. #endregion
  175. #region Private Methods (BST)
  176. /// <summary>
  177. /// Adds all nodes that are children of or contained within <paramref name="node"/> into <paramref name="list"/>, in Key Order.
  178. /// </summary>
  179. /// <param name="node">The node to search for nodes within</param>
  180. /// <param name="list">The list to add node to</param>
  181. private void AddToList(Node<K, V> node, List<KeyValuePair<K, V>> list)
  182. {
  183. if (node == null)
  184. {
  185. return;
  186. }
  187. AddToList(node.Left, list);
  188. list.Add(new KeyValuePair<K, V>(node.Key, node.Value));
  189. AddToList(node.Right, list);
  190. }
  191. /// <summary>
  192. /// Retrieve the node reference whose key is <paramref name="key"/>, or null if no such node exists.
  193. /// </summary>
  194. /// <param name="key">Key of the node to get</param>
  195. /// <returns>Node reference in the tree</returns>
  196. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  197. private Node<K, V> GetNode(K key)
  198. {
  199. if (key == null)
  200. {
  201. throw new ArgumentNullException(nameof(key));
  202. }
  203. Node<K, V> node = _root;
  204. while (node != null)
  205. {
  206. int cmp = key.CompareTo(node.Key);
  207. if (cmp < 0)
  208. {
  209. node = node.Left;
  210. }
  211. else if (cmp > 0)
  212. {
  213. node = node.Right;
  214. }
  215. else
  216. {
  217. return node;
  218. }
  219. }
  220. return null;
  221. }
  222. /// <summary>
  223. /// Inserts a new node into the tree whose key is <paramref name="key"/> and value is <paramref name="value"/>.
  224. /// <br></br>
  225. /// Adding the same key multiple times will overwrite the previous value.
  226. /// </summary>
  227. /// <param name="key">Key of the node to insert</param>
  228. /// <param name="value">Value of the node to insert</param>
  229. private void Insert(K key, V value)
  230. {
  231. Node<K, V> newNode = BSTInsert(key, value);
  232. RestoreBalanceAfterInsertion(newNode);
  233. }
  234. /// <summary>
  235. /// Insertion Mechanism for a Binary Search Tree (BST).
  236. /// <br></br>
  237. /// Iterates the tree starting from the root and inserts a new node where all children in the left subtree are less than <paramref name="key"/>, and all children in the right subtree are greater than <paramref name="key"/>.
  238. /// <br></br>
  239. /// <b>Note: </b> If a node whose key is <paramref name="key"/> already exists, it's value will be overwritten.
  240. /// </summary>
  241. /// <param name="key">Key of the node to insert</param>
  242. /// <param name="value">Value of the node to insert</param>
  243. /// <returns>The inserted Node</returns>
  244. private Node<K, V> BSTInsert(K key, V value)
  245. {
  246. Node<K, V> parent = null;
  247. Node<K, V> node = _root;
  248. while (node != null)
  249. {
  250. parent = node;
  251. int cmp = key.CompareTo(node.Key);
  252. if (cmp < 0)
  253. {
  254. node = node.Left;
  255. }
  256. else if (cmp > 0)
  257. {
  258. node = node.Right;
  259. }
  260. else
  261. {
  262. node.Value = value;
  263. return node;
  264. }
  265. }
  266. Node<K, V> newNode = new Node<K, V>(key, value, parent);
  267. if (newNode.Parent == null)
  268. {
  269. _root = newNode;
  270. }
  271. else if (key.CompareTo(parent.Key) < 0)
  272. {
  273. parent.Left = newNode;
  274. }
  275. else
  276. {
  277. parent.Right = newNode;
  278. }
  279. _count++;
  280. return newNode;
  281. }
  282. /// <summary>
  283. /// Removes <paramref name="key"/> from the dictionary, if it exists.
  284. /// </summary>
  285. /// <param name="key">Key of the node to delete</param>
  286. /// <returns>The deleted Node</returns>
  287. private Node<K, V> Delete(K key)
  288. {
  289. // O(1) Retrieval
  290. Node<K, V> nodeToDelete = GetNode(key);
  291. if (nodeToDelete == null) return null;
  292. Node<K, V> replacementNode;
  293. if (LeftOf(nodeToDelete) == null || RightOf(nodeToDelete) == null)
  294. {
  295. replacementNode = nodeToDelete;
  296. }
  297. else
  298. {
  299. replacementNode = PredecessorOf(nodeToDelete);
  300. }
  301. Node<K, V> tmp = LeftOf(replacementNode) ?? RightOf(replacementNode);
  302. if (tmp != null)
  303. {
  304. tmp.Parent = ParentOf(replacementNode);
  305. }
  306. if (ParentOf(replacementNode) == null)
  307. {
  308. _root = tmp;
  309. }
  310. else if (replacementNode == LeftOf(ParentOf(replacementNode)))
  311. {
  312. ParentOf(replacementNode).Left = tmp;
  313. }
  314. else
  315. {
  316. ParentOf(replacementNode).Right = tmp;
  317. }
  318. if (replacementNode != nodeToDelete)
  319. {
  320. nodeToDelete.Key = replacementNode.Key;
  321. nodeToDelete.Value = replacementNode.Value;
  322. }
  323. if (tmp != null && ColorOf(replacementNode) == Black)
  324. {
  325. RestoreBalanceAfterRemoval(tmp);
  326. }
  327. return replacementNode;
  328. }
  329. /// <summary>
  330. /// Returns the node with the largest key where <paramref name="node"/> is considered the root node.
  331. /// </summary>
  332. /// <param name="node">Root Node</param>
  333. /// <returns>Node with the maximum key in the tree of <paramref name="node"/></returns>
  334. private static Node<K, V> Maximum(Node<K, V> node)
  335. {
  336. Node<K, V> tmp = node;
  337. while (tmp.Right != null)
  338. {
  339. tmp = tmp.Right;
  340. }
  341. return tmp;
  342. }
  343. /// <summary>
  344. /// Returns the node with the smallest key where <paramref name="node"/> is considered the root node.
  345. /// </summary>
  346. /// <param name="node">Root Node</param>
  347. /// <returns>Node with the minimum key in the tree of <paramref name="node"/></returns>
  348. ///<exception cref="ArgumentNullException"><paramref name="node"/> is null</exception>
  349. private static Node<K, V> Minimum(Node<K, V> node)
  350. {
  351. if (node == null)
  352. {
  353. throw new ArgumentNullException(nameof(node));
  354. }
  355. Node<K, V> tmp = node;
  356. while (tmp.Left != null)
  357. {
  358. tmp = tmp.Left;
  359. }
  360. return tmp;
  361. }
  362. /// <summary>
  363. /// Returns the node whose key immediately less than or equal to <paramref name="key"/>.
  364. /// </summary>
  365. /// <param name="key">Key for which to find the floor node of</param>
  366. /// <returns>Node whose key is immediately less than or equal to <paramref name="key"/>, or null if no such node is found.</returns>
  367. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  368. private Node<K, V> FloorNode(K key)
  369. {
  370. if (key == null)
  371. {
  372. throw new ArgumentNullException(nameof(key));
  373. }
  374. Node<K, V> tmp = _root;
  375. while (tmp != null)
  376. {
  377. int cmp = key.CompareTo(tmp.Key);
  378. if (cmp > 0)
  379. {
  380. if (tmp.Right != null)
  381. {
  382. tmp = tmp.Right;
  383. }
  384. else
  385. {
  386. return tmp;
  387. }
  388. }
  389. else if (cmp < 0)
  390. {
  391. if (tmp.Left != null)
  392. {
  393. tmp = tmp.Left;
  394. }
  395. else
  396. {
  397. Node<K, V> parent = tmp.Parent;
  398. Node<K, V> ptr = tmp;
  399. while (parent != null && ptr == parent.Left)
  400. {
  401. ptr = parent;
  402. parent = parent.Parent;
  403. }
  404. return parent;
  405. }
  406. }
  407. else
  408. {
  409. return tmp;
  410. }
  411. }
  412. return null;
  413. }
  414. /// <summary>
  415. /// Returns the node whose key is immediately greater than or equal to than <paramref name="key"/>.
  416. /// </summary>
  417. /// <param name="key">Key for which to find the ceiling node of</param>
  418. /// <returns>Node whose key is immediately greater than or equal to <paramref name="key"/>, or null if no such node is found.</returns>
  419. /// <exception cref="ArgumentNullException"><paramref name="key"/> is null</exception>
  420. private Node<K, V> CeilingNode(K key)
  421. {
  422. if (key == null)
  423. {
  424. throw new ArgumentNullException(nameof(key));
  425. }
  426. Node<K, V> tmp = _root;
  427. while (tmp != null)
  428. {
  429. int cmp = key.CompareTo(tmp.Key);
  430. if (cmp < 0)
  431. {
  432. if (tmp.Left != null)
  433. {
  434. tmp = tmp.Left;
  435. }
  436. else
  437. {
  438. return tmp;
  439. }
  440. }
  441. else if (cmp > 0)
  442. {
  443. if (tmp.Right != null)
  444. {
  445. tmp = tmp.Right;
  446. }
  447. else
  448. {
  449. Node<K, V> parent = tmp.Parent;
  450. Node<K, V> ptr = tmp;
  451. while (parent != null && ptr == parent.Right)
  452. {
  453. ptr = parent;
  454. parent = parent.Parent;
  455. }
  456. return parent;
  457. }
  458. }
  459. else
  460. {
  461. return tmp;
  462. }
  463. }
  464. return null;
  465. }
  466. /// <summary>
  467. /// Finds the node with the key is immediately greater than <paramref name="node"/>.
  468. /// </summary>
  469. /// <param name="node">Node to find the successor of</param>
  470. /// <returns>Successor of <paramref name="node"/></returns>
  471. private static Node<K, V> SuccessorOf(Node<K, V> node)
  472. {
  473. if (node.Right != null)
  474. {
  475. return Minimum(node.Right);
  476. }
  477. Node<K, V> parent = node.Parent;
  478. while (parent != null && node == parent.Right)
  479. {
  480. node = parent;
  481. parent = parent.Parent;
  482. }
  483. return parent;
  484. }
  485. /// <summary>
  486. /// Finds the node whose key is immediately less than <paramref name="node"/>.
  487. /// </summary>
  488. /// <param name="node">Node to find the predecessor of</param>
  489. /// <returns>Predecessor of <paramref name="node"/></returns>
  490. private static Node<K, V> PredecessorOf(Node<K, V> node)
  491. {
  492. if (node.Left != null)
  493. {
  494. return Maximum(node.Left);
  495. }
  496. Node<K, V> parent = node.Parent;
  497. while (parent != null && node == parent.Left)
  498. {
  499. node = parent;
  500. parent = parent.Parent;
  501. }
  502. return parent;
  503. }
  504. #endregion
  505. #region Private Methods (RBL)
  506. private void RestoreBalanceAfterRemoval(Node<K, V> balanceNode)
  507. {
  508. Node<K, V> ptr = balanceNode;
  509. while (ptr != _root && ColorOf(ptr) == Black)
  510. {
  511. if (ptr == LeftOf(ParentOf(ptr)))
  512. {
  513. Node<K, V> sibling = RightOf(ParentOf(ptr));
  514. if (ColorOf(sibling) == Red)
  515. {
  516. SetColor(sibling, Black);
  517. SetColor(ParentOf(ptr), Red);
  518. RotateLeft(ParentOf(ptr));
  519. sibling = RightOf(ParentOf(ptr));
  520. }
  521. if (ColorOf(LeftOf(sibling)) == Black && ColorOf(RightOf(sibling)) == Black)
  522. {
  523. SetColor(sibling, Red);
  524. ptr = ParentOf(ptr);
  525. }
  526. else
  527. {
  528. if (ColorOf(RightOf(sibling)) == Black)
  529. {
  530. SetColor(LeftOf(sibling), Black);
  531. SetColor(sibling, Red);
  532. RotateRight(sibling);
  533. sibling = RightOf(ParentOf(ptr));
  534. }
  535. SetColor(sibling, ColorOf(ParentOf(ptr)));
  536. SetColor(ParentOf(ptr), Black);
  537. SetColor(RightOf(sibling), Black);
  538. RotateLeft(ParentOf(ptr));
  539. ptr = _root;
  540. }
  541. }
  542. else
  543. {
  544. Node<K, V> sibling = LeftOf(ParentOf(ptr));
  545. if (ColorOf(sibling) == Red)
  546. {
  547. SetColor(sibling, Black);
  548. SetColor(ParentOf(ptr), Red);
  549. RotateRight(ParentOf(ptr));
  550. sibling = LeftOf(ParentOf(ptr));
  551. }
  552. if (ColorOf(RightOf(sibling)) == Black && ColorOf(LeftOf(sibling)) == Black)
  553. {
  554. SetColor(sibling, Red);
  555. ptr = ParentOf(ptr);
  556. }
  557. else
  558. {
  559. if (ColorOf(LeftOf(sibling)) == Black)
  560. {
  561. SetColor(RightOf(sibling), Black);
  562. SetColor(sibling, Red);
  563. RotateLeft(sibling);
  564. sibling = LeftOf(ParentOf(ptr));
  565. }
  566. SetColor(sibling, ColorOf(ParentOf(ptr)));
  567. SetColor(ParentOf(ptr), Black);
  568. SetColor(LeftOf(sibling), Black);
  569. RotateRight(ParentOf(ptr));
  570. ptr = _root;
  571. }
  572. }
  573. }
  574. SetColor(ptr, Black);
  575. }
  576. private void RestoreBalanceAfterInsertion(Node<K, V> balanceNode)
  577. {
  578. SetColor(balanceNode, Red);
  579. while (balanceNode != null && balanceNode != _root && ColorOf(ParentOf(balanceNode)) == Red)
  580. {
  581. if (ParentOf(balanceNode) == LeftOf(ParentOf(ParentOf(balanceNode))))
  582. {
  583. Node<K, V> sibling = RightOf(ParentOf(ParentOf(balanceNode)));
  584. if (ColorOf(sibling) == Red)
  585. {
  586. SetColor(ParentOf(balanceNode), Black);
  587. SetColor(sibling, Black);
  588. SetColor(ParentOf(ParentOf(balanceNode)), Red);
  589. balanceNode = ParentOf(ParentOf(balanceNode));
  590. }
  591. else
  592. {
  593. if (balanceNode == RightOf(ParentOf(balanceNode)))
  594. {
  595. balanceNode = ParentOf(balanceNode);
  596. RotateLeft(balanceNode);
  597. }
  598. SetColor(ParentOf(balanceNode), Black);
  599. SetColor(ParentOf(ParentOf(balanceNode)), Red);
  600. RotateRight(ParentOf(ParentOf(balanceNode)));
  601. }
  602. }
  603. else
  604. {
  605. Node<K, V> sibling = LeftOf(ParentOf(ParentOf(balanceNode)));
  606. if (ColorOf(sibling) == Red)
  607. {
  608. SetColor(ParentOf(balanceNode), Black);
  609. SetColor(sibling, Black);
  610. SetColor(ParentOf(ParentOf(balanceNode)), Red);
  611. balanceNode = ParentOf(ParentOf(balanceNode));
  612. }
  613. else
  614. {
  615. if (balanceNode == LeftOf(ParentOf(balanceNode)))
  616. {
  617. balanceNode = ParentOf(balanceNode);
  618. RotateRight(balanceNode);
  619. }
  620. SetColor(ParentOf(balanceNode), Black);
  621. SetColor(ParentOf(ParentOf(balanceNode)), Red);
  622. RotateLeft(ParentOf(ParentOf(balanceNode)));
  623. }
  624. }
  625. }
  626. SetColor(_root, Black);
  627. }
  628. private void RotateLeft(Node<K, V> node)
  629. {
  630. if (node != null)
  631. {
  632. Node<K, V> right = RightOf(node);
  633. node.Right = LeftOf(right);
  634. if (LeftOf(right) != null)
  635. {
  636. LeftOf(right).Parent = node;
  637. }
  638. right.Parent = ParentOf(node);
  639. if (ParentOf(node) == null)
  640. {
  641. _root = right;
  642. }
  643. else if (node == LeftOf(ParentOf(node)))
  644. {
  645. ParentOf(node).Left = right;
  646. }
  647. else
  648. {
  649. ParentOf(node).Right = right;
  650. }
  651. right.Left = node;
  652. node.Parent = right;
  653. }
  654. }
  655. private void RotateRight(Node<K, V> node)
  656. {
  657. if (node != null)
  658. {
  659. Node<K, V> left = LeftOf(node);
  660. node.Left = RightOf(left);
  661. if (RightOf(left) != null)
  662. {
  663. RightOf(left).Parent = node;
  664. }
  665. left.Parent = node.Parent;
  666. if (ParentOf(node) == null)
  667. {
  668. _root = left;
  669. }
  670. else if (node == RightOf(ParentOf(node)))
  671. {
  672. ParentOf(node).Right = left;
  673. }
  674. else
  675. {
  676. ParentOf(node).Left = left;
  677. }
  678. left.Right = node;
  679. node.Parent = left;
  680. }
  681. }
  682. #endregion
  683. #region Safety-Methods
  684. // These methods save memory by allowing us to forego sentinel nil nodes, as well as serve as protection against NullReferenceExceptions.
  685. /// <summary>
  686. /// Returns the color of <paramref name="node"/>, or Black if it is null.
  687. /// </summary>
  688. /// <param name="node">Node</param>
  689. /// <returns>The boolean color of <paramref name="node"/>, or black if null</returns>
  690. private static bool ColorOf(Node<K, V> node)
  691. {
  692. return node == null || node.Color;
  693. }
  694. /// <summary>
  695. /// Sets the color of <paramref name="node"/> node to <paramref name="color"/>.
  696. /// <br></br>
  697. /// This method does nothing if <paramref name="node"/> is null.
  698. /// </summary>
  699. /// <param name="node">Node to set the color of</param>
  700. /// <param name="color">Color (Boolean)</param>
  701. private static void SetColor(Node<K, V> node, bool color)
  702. {
  703. if (node != null)
  704. {
  705. node.Color = color;
  706. }
  707. }
  708. /// <summary>
  709. /// This method returns the left node of <paramref name="node"/>, or null if <paramref name="node"/> is null.
  710. /// </summary>
  711. /// <param name="node">Node to retrieve the left child from</param>
  712. /// <returns>Left child of <paramref name="node"/></returns>
  713. private static Node<K, V> LeftOf(Node<K, V> node)
  714. {
  715. return node?.Left;
  716. }
  717. /// <summary>
  718. /// This method returns the right node of <paramref name="node"/>, or null if <paramref name="node"/> is null.
  719. /// </summary>
  720. /// <param name="node">Node to retrieve the right child from</param>
  721. /// <returns>Right child of <paramref name="node"/></returns>
  722. private static Node<K, V> RightOf(Node<K, V> node)
  723. {
  724. return node?.Right;
  725. }
  726. /// <summary>
  727. /// Returns the parent node of <paramref name="node"/>, or null if <paramref name="node"/> is null.
  728. /// </summary>
  729. /// <param name="node">Node to retrieve the parent from</param>
  730. /// <returns>Parent of <paramref name="node"/></returns>
  731. private static Node<K, V> ParentOf(Node<K, V> node)
  732. {
  733. return node?.Parent;
  734. }
  735. #endregion
  736. #region Interface Implementations
  737. // Method descriptions are not provided as they are already included as part of the interface.
  738. public bool ContainsKey(K key)
  739. {
  740. if (key == null)
  741. {
  742. throw new ArgumentNullException(nameof(key));
  743. }
  744. return GetNode(key) != null;
  745. }
  746. bool IDictionary<K, V>.Remove(K key)
  747. {
  748. int count = _count;
  749. Remove(key);
  750. return count > _count;
  751. }
  752. public bool TryGetValue(K key, [MaybeNullWhen(false)] out V value)
  753. {
  754. if (null == key)
  755. {
  756. throw new ArgumentNullException(nameof(key));
  757. }
  758. Node<K, V> node = GetNode(key);
  759. value = node != null ? node.Value : default;
  760. return node != null;
  761. }
  762. public void Add(KeyValuePair<K, V> item)
  763. {
  764. if (item.Key == null)
  765. {
  766. throw new ArgumentNullException(nameof(item.Key));
  767. }
  768. Add(item.Key, item.Value);
  769. }
  770. public void Clear()
  771. {
  772. _root = null;
  773. _count = 0;
  774. }
  775. public bool Contains(KeyValuePair<K, V> item)
  776. {
  777. if (item.Key == null)
  778. {
  779. return false;
  780. }
  781. Node<K, V> node = GetNode(item.Key);
  782. if (node != null)
  783. {
  784. return node.Key.Equals(item.Key) && node.Value.Equals(item.Value);
  785. }
  786. return false;
  787. }
  788. public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex)
  789. {
  790. if (arrayIndex < 0 || array.Length - arrayIndex < this.Count)
  791. {
  792. throw new ArgumentOutOfRangeException(nameof(arrayIndex));
  793. }
  794. SortedList<K, V> list = GetKeyValues();
  795. int offset = 0;
  796. for (int i = arrayIndex; i < array.Length && offset < list.Count; i++)
  797. {
  798. array[i] = new KeyValuePair<K, V>(list.Keys[i], list.Values[i]);
  799. offset++;
  800. }
  801. }
  802. public bool Remove(KeyValuePair<K, V> item)
  803. {
  804. Node<K, V> node = GetNode(item.Key);
  805. if (node == null)
  806. {
  807. return false;
  808. }
  809. if (node.Value.Equals(item.Value))
  810. {
  811. int count = _count;
  812. Remove(item.Key);
  813. return count > _count;
  814. }
  815. return false;
  816. }
  817. public IEnumerator<KeyValuePair<K, V>> GetEnumerator()
  818. {
  819. return GetKeyValues().GetEnumerator();
  820. }
  821. IEnumerator IEnumerable.GetEnumerator()
  822. {
  823. return GetKeyValues().GetEnumerator();
  824. }
  825. public int Count => _count;
  826. public ICollection<K> Keys => GetKeyValues().Keys;
  827. public ICollection<V> Values => GetKeyValues().Values;
  828. public bool IsReadOnly => false;
  829. public V this[K key]
  830. {
  831. get => Get(key);
  832. set => Add(key, value);
  833. }
  834. #endregion
  835. #region Private Interface Helper Methods
  836. /// <summary>
  837. /// Returns a sorted list of all the node keys / values in the tree.
  838. /// </summary>
  839. /// <returns>List of node keys</returns>
  840. private SortedList<K, V> GetKeyValues()
  841. {
  842. SortedList<K, V> set = new SortedList<K, V>();
  843. Queue<Node<K, V>> queue = new Queue<Node<K, V>>();
  844. if (_root != null)
  845. {
  846. queue.Enqueue(_root);
  847. }
  848. while (queue.Count > 0)
  849. {
  850. Node<K, V> node = queue.Dequeue();
  851. set.Add(node.Key, node.Value);
  852. if (null != node.Left)
  853. {
  854. queue.Enqueue(node.Left);
  855. }
  856. if (null != node.Right)
  857. {
  858. queue.Enqueue(node.Right);
  859. }
  860. }
  861. return set;
  862. }
  863. #endregion
  864. }
  865. /// <summary>
  866. /// Represents a node in the TreeDictionary which contains a key and value of generic type K and V, respectively.
  867. /// </summary>
  868. /// <typeparam name="K">Key of the node</typeparam>
  869. /// <typeparam name="V">Value of the node</typeparam>
  870. class Node<K, V>
  871. {
  872. public bool Color = true;
  873. public Node<K, V> Left = null;
  874. public Node<K, V> Right = null;
  875. public Node<K, V> Parent = null;
  876. public K Key;
  877. public V Value;
  878. public Node(K key, V value, Node<K, V> parent)
  879. {
  880. Key = key;
  881. Value = value;
  882. Parent = parent;
  883. }
  884. }
  885. }