Skip to content

Prevent stack overflow in BST deletion - #90

Closed
krotname wants to merge 1 commit into
mainfrom
codex/propose-fix-for-recursive-bst-delete-crash
Closed

Prevent stack overflow in BST deletion#90
krotname wants to merge 1 commit into
mainfrom
codex/propose-fix-for-recursive-bst-delete-crash

Conversation

@krotname

@krotname krotname commented Aug 1, 2026

Copy link
Copy Markdown
Owner

Motivation

  • The public Solution.remove(Node,int) implementation used unbounded recursion proportional to tree height, which can trigger StackOverflowError on deeply skewed (attacker-controlled) trees and cause availability failures.
  • The goal is to eliminate the recursive stack growth while preserving existing deletion semantics (leaf, one-child, two-child using predecessor) and tests.

Description

  • Replace recursive lookup-and-delete with an iterative search using parent and current pointers to avoid per-level Java stack frames during traversal.
  • Handle nodes with two children by locating and detaching the predecessor iteratively (no recursive call) and copying its value to the deleted node, preserving predecessor-based behavior.
  • Remove the recursive findMax/recursive-delete path and return/update child links iteratively; overall auxiliary space becomes O(1).
  • Add a regression test removeHandlesDeepSkewedTreeWithoutOverflowingStack that constructs a 100,000-node right-skewed tree and deletes the deepest node to verify no stack overflow and correct tree shape.

Testing

  • Ran mvn -Dtest=algorithms.sprint5.SolutionTest test, and the module-specific tests passed (5 tests, all successful).
  • Ran full test suite with mvn test, and all automated tests passed (598 tests, all successful).

Codex Task

@krotname

krotname commented Aug 1, 2026

Copy link
Copy Markdown
Owner Author

Superseded by the validated combined merge in #115: #115

@krotname krotname closed this Aug 1, 2026
@krotname
krotname deleted the codex/propose-fix-for-recursive-bst-delete-crash branch August 1, 2026 02:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant