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 / successorIntermediate
Balanced BSTHow balancing worksO(log n)O(n)Comparable valuesEverything a BST does at guaranteed O(log n); range queries, k-th smallestHard
TrieTriesO(L)O(ΣL)Characters of a stringInsert, lookup, prefix lookupIntermediate
Segment TreeSegment treesO(log n)O(n)Array indexRange query (sum, max, min, anything mergeable), point or range updateHard
Fenwick Tree (BIT)Fenwick treesO(log n)O(n)Array indexPrefix sum, point updateHard

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.