TreeDictionary.cs 33 KB

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