Begin Algo
Tree · Comparison

Tree data structures compared

BST, balanced BST, trie, segment tree and Fenwick tree: the operations each supports, whether it handles updates, and which problem calls for which tree.

AlgorithmTimeSpaceKeyed byCore operationsUpdatesDifficulty
BSTBinary search treesO(h)O(h)Comparable valuesSearch, insert, delete, predecessor / successor✓Intermediate
Balanced BSTHow balancing worksO(log n)O(n)Comparable valuesEverything a BST does at guaranteed O(log n); range queries, k-th smallest✓Hard
TrieTriesO(L)O(ΣL)Characters of a stringInsert, lookup, prefix lookup✓Intermediate
Segment TreeSegment treesO(log n)O(n)Array indexRange query (sum, max, min, anything mergeable), point or range update✓Hard
Fenwick Tree (BIT)Fenwick treesO(log n)O(n)Array indexPrefix sum, point update✓Hard

When to pick which

Choosing guide

  • Ordered and changing → a balanced tree (use the built-in one). Only membership → a hash table is faster. Static data → a sorted array with binary search is enough.
  • Range sums, static → prefix sums (O(1) query). Range sums, with updates → Fenwick. Range max / min with updates → segment tree.
  • Range updates (add to or assign a whole range) → segment tree with lazy propagation. Fenwick only manages the 'range add, point query' variant.
  • String keys and prefix questions → a trie. String keys but only equality → a hash table; a trie has no edge.
  • k-th smallest, ranks → a balanced tree with subtree sizes, or a Fenwick tree over the value domain, which is easier to write once values are compressed.