TheAlgorithms/C-Sharp · error · InvalidOperationException
Tree is empty!
Error message
Tree is empty!
What it means
RedBlackTree<TKey>.GetMin throws InvalidOperationException when the tree's root is null, i.e. no keys have been inserted. The minimum is defined only over existing nodes, so an empty tree is an error rather than a default value.
Solutions
- Check the tree's Count/IsEmpty (or track insertion count) before calling GetMin.
- Ensure Add is called at least once before querying min.
- Catch InvalidOperationException and return a sentinel/default for empty trees.
- If trees are frequently empty, wrap access in a helper returning TKey?.
Example fix
// before
var min = tree.GetMin(); // throws if empty
// after
if (tree.Count > 0) { var min = tree.GetMin(); } Defensive patterns
Strategy: validation
Validate before calling
var min = tree.Count > 0 ? tree.GetMin() : default;
Try / catch
try
{
var min = tree.GetMin();
}
catch (InvalidOperationException)
{
// tree empty: no minimum
} Prevention
- Check Count > 0 before GetMin.
- Ensure at least one Add precedes min queries.
- Return TKey? via a helper for possibly-empty trees.
- Test min/max on empty trees explicitly.
When it happens
Trigger: Calling GetMin on a RedBlackTree constructed but never populated via Add, or after all keys were removed.
Common situations: Querying min before initialization, trees cleared between phases, or generic code that assumes the tree is non-empty (e.g. in constructor tests with custom comparers).
Understand the failure class
Background: EmptyResultError / "no results found": when an API or scraper succeeds but returns zero rows — this error's family across 9 libraries.
Related errors
- Tree is empty!
- Deque is empty.
- There are no items in the queue.
- The queue contains no items.
- Key " " already exists in tree!
AI-assisted analysis of TheAlgorithms/C-Sharp@96e2905cab (2026-09-13).
Data as JSON: /api/errors/f98ef909ae146771.
Report an issue: GitHub.
Appendix: source
Thrown at DataStructures/RedBlackTree/RedBlackTree.cs:209
}
else
{
return true;
}
}
return false;
}
/// <summary>
/// Get the minimum value in the tree.
/// </summary>
/// <returns>Minimum value in tree.</returns>
public TKey GetMin()
{
if (root is null)
{
throw new InvalidOperationException("Tree is empty!");
}
return GetMin(root).Key;
}
/// <summary>
/// Get the maximum value in the tree.
/// </summary>
/// <returns>Maximum value in tree.</returns>
public TKey GetMax()
{
if (root is null)
{
throw new InvalidOperationException("Tree is empty!");
}
return GetMax(root).Key;
}View on GitHub (pinned to 96e2905cab)