binary-search-tree/red-black-tree Home Manual Reference Source

src/swap/swap_non_adjacent.js

  1. import assert from 'assert';
  2. import Node from '../types/Node.js';
  3. import swap_color from './swap_color.js';
  4.  
  5. /**
  6. * Swap pointers and colors of two NON-ADJACENT nodes with three constraints:
  7. * - B is not the root
  8. * - B is its parent right child
  9. * - B's right child is a leaf
  10. *
  11. * NOTE: These three constraints are implied because B is A's in-subtree
  12. * predecessor without being A's left child.
  13. *
  14. * p q q p
  15. * | \ \ |
  16. * -A +B +A -B
  17. * / \ / \ / \ / \
  18. * u v x - -> x - u v
  19. *
  20. * @param {Node} A - The first node.
  21. * @param {Node} B - The second node.
  22. */
  23.  
  24. const swap_non_adjacent = (A, B) => {
  25. assert(A instanceof Node);
  26. assert(B instanceof Node);
  27. const p = A.parent;
  28. const u = A.left;
  29. const v = A.right;
  30. const q = B.parent;
  31. const x = B.left;
  32. assert(B.right === null);
  33. assert(q !== null);
  34. assert(B === q.right);
  35.  
  36. if (p !== null) {
  37. if (A === p.left) p.left = B;
  38. else p.right = B;
  39. }
  40.  
  41. q.right = A;
  42.  
  43. A.parent = q;
  44. A.left = x;
  45. A.right = null;
  46. B.parent = p;
  47. B.left = u;
  48. B.right = v;
  49.  
  50. if (x !== null) x.parent = A;
  51. if (u !== null) u.parent = B;
  52. if (v !== null) v.parent = B;
  53.  
  54. swap_color(A, B);
  55. };
  56.  
  57. export default swap_non_adjacent;