Skip to content

Fix red-black tree insertion invariants - #2248

Open
Shubham-Padkonde wants to merge 1 commit into
trekhleb:masterfrom
Shubham-Padkonde:fix/red-black-tree-insertion-invariants
Open

Shubham-Padkonde wants to merge 1 commit into
trekhleb:masterfrom
Shubham-Padkonde:fix/red-black-tree-insertion-invariants

Conversation

@Shubham-Padkonde

Copy link
Copy Markdown

Inserting [1, 3, 2, 4, 5] currently loses two keys; other sequences in #2229 throw or produce unequal black heights. Preserve parent ownership when a rotation replaces an already-reparented child, and stop balancing a black subtree root after a rotation. The latter cannot introduce a red/red violation and rotating it again can invalidate the tree.

Fixes #2229. Thanks to @devladpopov for the reproducible invariant failures.

Related to the existing proposal #561: that patch repairs parent pointers locally in the two double rotations. This change addresses the underlying child-setter ownership behavior, including single rotations below another ancestor, and the separate black-node balancing defect. Fixing parent links alone still fails two of the new invariant cases. I am linking the overlap explicitly so maintainers can choose how to integrate the proposals.

The tests verify sorted membership, parent pointers, root color, adjacent red nodes, and equal black heights after every insertion. They cover the reported sequences and their mirrors, plus all 720 permutations of six keys. Child-setter tests also confirm that ordinary removal still clears the parent.

Validation:

  • All nine new tests fail on the original implementation.
  • All 596 tests across 179 suites pass after the fix.
  • npm run lint and git diff --check pass.
  • Both changed source files have 100% statement, function, and line coverage in the tree suite; combined branch coverage is 97.89%.

AI assistance: implementation and tests were prepared with Codex and validated using the checks above.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

RedBlackTree: insert loses nodes (e.g. 1,3,2,4,5 -> "3,4,5"); two root causes not covered by #561

1 participant