Skip to content

perf: cache binary tree node heights - #2254

Open
sshnox wants to merge 2 commits into
trekhleb:masterfrom
sshnox:fix/cache-avl-node-heights
Open

sshnox wants to merge 2 commits into
trekhleb:masterfrom
sshnox:fix/cache-avl-node-heights

Conversation

@sshnox

@sshnox sshnox commented Nov 10, 2026

Copy link
Copy Markdown

Summary

  • Cache each binary tree node's subtree height instead of recalculating it recursively.
  • Propagate height changes through child mutations and refresh cached heights after AVL removal.
  • Add regression coverage for cached heights after child removal.

Fixes #2235

Validation

  • npm test -- --runInBand --coverage=false — 178 test suites and 587 tests passed.
  • npm run lint — passed.
  • git diff --check — passed.

Co-authored-by: Manus <dev-agent@manus.ai>
@lazarljubenovic

Copy link
Copy Markdown

Why tho?

Keep the new parent when a rotation reattaches a child before clearing its old slot. Cover both directions with insertions into the transferred subtree.
@sshnox

sshnox commented Nov 13, 2026

Copy link
Copy Markdown
Author

Why tho?

Thanks for asking. This addresses the performance issue in #2235. The existing height getters recursively traverse subtrees, and AVL balancing evaluates them repeatedly while walking ancestors, leading to substantially more work than the expected O(log n) insertion.

The change caches subtree heights and updates affected ancestors when children change. I've also added regression coverage for rotations and child removal.

The existing deletion path still requires a subtree-height refresh, so I'm not claiming O(log n) deletion performance with this change.

Local validation reported 587 passing tests and successful linting. I'm happy to add before/after benchmarks if that would help with review.

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.

AvlTree: insert is O(n) because height/balanceFactor are recomputed recursively (README claims O(log n))

2 participants