Skip to content

Size balanced trees lose the size balanced property and grow far beyond the AVL height bound #115

Done

Description

@konard

Problem

The size balanced trees in this repository can grow far beyond the height a size balanced tree may have. Found in linksplatform/Data.Doublets#577: in the united memory store, links that share one source are created alternately with unrelated links, and the source index degenerates into long paths.

Chen's size balanced tree (2007) guarantees that every child is at least as large as both children of its sibling. The smallest such tree of height h has m(h) = m(h-1) + m(h-2) + 1 nodes, the same as for AVL trees, so the height never exceeds about 1.44 * log2(n). The current code does not keep that property:

Variant Defect
C# SizeBalancedTreeMethods attachCount/maintainThreashold (added for #103) skips Maintain on every second attach; DetachCore never runs Maintain.
C# RecursionlessSizeBalancedTreeMethods A one-pass rotation heuristic, not Chen's algorithm: it checks only one level and never repairs the subtrees changed by its rotations. Same for detach.
C++ SizeBalancedTreeMethods Attach is Chen's algorithm, but DetachCore never runs Maintain.
C++ RecursionlessSizeBalancedTreeMethods The same heuristic as in C#.

Rust has no size balanced tree.

Reproduction

Attach 1, N+1, 2, N+2, 3, N+3, ... (a hot range interleaved with a cold range) and measure the height. With the C# threshold, the recursive tree built from 1, 5, 2, 6, 3, 7, 4, 8 has 5 levels (an AVL tree of 8 nodes has at most 4), and with 2,048 hot and 2,048 cold keys it has 2,049 levels (bound 16): the hot half is a linked list. The C# recursionless tree has 17 levels for the same 4,096 keys, the C++ one 19 levels for 8,192 keys (bound 18). In C++, attaching 1..4096 and detaching every node except the path from the root to key 1 leaves the recursive tree with 12 nodes in 12 levels (bound 5), because detach never rebalances.

Fix

#116 restores Chen's algorithm in all four variants, adds tests that fail before the fix, and rebuilds, once in linear time, trees that older versions have already stored in a degenerate shape.

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions