Skip to content

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

Open

Description

@devladpopov

BinaryTreeNode.height, leftHeight, rightHeight and balanceFactor (lines 25–55) are recursive getters with no caching, and AvlTree.balance() evaluates them on every ancestor. Counting calls to the height getter per insert:

tree size n 500 1,000 2,000 4,000
height calls / insert 2,384 4,390 8,249 15,822

That grows linearly with n, so building a tree is O(n²). Fix: store height on the node and update it on attach and rotation. (Independent of the correctness bugs in #325 and #485.)


Found during an independent property-based audit of this repo (full report and reproducible harness: https://github.com/devladpopov/algorithm-autopsy/tree/main/autopsy-02).

Activity

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions