Skip to content

testRedBlackPropertyViolation() optimization #68

Description

@odorovskoy

/**
* Warning this function is very expensive.
*/
template <typename TreeT>
void testRedBlackPropertyViolation(TreeT const& tree)

I don't think it has to be that expensive. Red-black tree properties are:

  1. Every node is either red or black.
  2. The root node must be black.
  3. All leaf nodes (null or NIL nodes) are considered black.
  4. If a node is red, then both its children must be black (no two consecutive red nodes).
  5. Every path from a given node to any of its descendant leaf nodes contains the same number of black nodes.

It should be possible to check all of these not only in linear time, but in one pass over the tree. Current implementation seems to be checking the 5th item twice:

  • using blackHeight recursive function (linear)
  • using leafCollector + the loop in the end of the function (lines 75-97). This is $O(n^2)$, since it recomputes paths from the leaves to each node again and again.

The second is ineffective and redundant. Removing it and moving all per-node checks inside the function which traverses a tree allows running all checks in one pass. This should allow running tree violation checks more often in unit tests. I will prepare a PR shortly.

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