TExcelTAD
Home › Advanced & Succinct Data Structures › Succinct Trees with Balanced Parentheses

Succinct Trees with Balanced Parentheses

An ordinal tree (rooted, with ordered children) on nn nodes needs about 2n2n bits (space lower bounds), but a pointer representation spends Θ(nlg⁡n)\Theta(n \lg n). The balanced-parentheses (BP) representation (Jacobson 1989; Munro and Raman 1997, 2001) stores the tree in 2n2n bits plus o(n)o(n) bits of index and still answers PARENT, FIRST-CHILD, NEXT-SIBLING, SUBTREE-SIZE, DEPTH and preorder rank in O(1)O(1) time. This lesson is an introduction: it builds the representation, implements the navigation with a simple block index (O(b+n/b)O(b + n/b) time per operation instead of O(1)O(1)) and describes how the constant-time version works.

The representation

Walk the tree in depth-first order. Write ( when the walk enters a node and ) when it leaves it. Every node contributes one matched pair, so the sequence has 2n2n symbols, stored as bits (1 for "(", 0 for ")"). A node is identified with the position of its opening parenthesis.

Define the excess E(j)E(j) as the number of "(" minus the number of ")" in positions 0..j0..j. Every navigation operation becomes a search for a position with a given excess:

Operation Formula on the parentheses
FIND-CLOSE(v)(v) (the matching ")") smallest j>vj > v with E(j)=E(v)−1E(j) = E(v) - 1
PARENT(v)(v) (largest j<vj < v with E(j)=E(v)−2E(j) = E(v) - 2) +1+ 1
FIRST-CHILD(v)(v) v+1v + 1 if position v+1v + 1 is "(", else none
NEXT-SIBLING(v)(v) FIND-CLOSE(v)+1(v) + 1 if that position is "(", else none
SUBTREE-SIZE(v)(v) (FIND-CLOSE(v)−v+1)/2(\text{FIND-CLOSE}(v) - v + 1) / 2
DEPTH(v)(v) E(v)E(v) (the root has depth 1)
PREORDER(v)(v) number of "(" before vv: (v+E(v)−1)/2(v + E(v) - 1)/2, a rank query

The excess changes by exactly ±1\pm 1 per position. So a forward search for a target below the current excess stops at the first position whose excess is at most the target, and to skip a block of positions it is enough to know the minimum excess inside it. The program stores the excess array and the minimum of each block of bb positions, and searches by scanning the rest of the current block, skipping blocks whose minimum is above the target, and scanning the block where the target is reached.

python · try it yourself
import random

class BPTree:
    """Ordinal tree as balanced parentheses: '(' = 1 when a DFS enters a node, ')' = 0 when it leaves.
    A node is the position of its '('. Navigation = searches for a given excess, sped up by
    storing the minimum excess of every block of b positions (a one-level range min-max directory)."""
    def __init__(self, bits, b=16):
        self.bits, self.b, self.n = bits, b, len(bits)
        self.E, e = [], 0                              # E[j] = excess of bits[0..j] (opens - closes)
        for x in bits:
            e += 1 if x else -1
            self.E.append(e)
        self.bmin = [min(self.E[i:i + b]) for i in range(0, self.n, b)]
        self.steps = 0
    def _exc(self, j):
        return 0 if j < 0 else self.E[j]
    def fwd(self, i, target):                          # smallest j > i with E[j] == target
        j = i + 1
        while j < self.n and j % self.b:               # rest of i's block
            self.steps += 1
            if self.E[j] == target: return j
            j += 1
        blk = j // self.b
        while blk < len(self.bmin) and self.bmin[blk] > target:   # skip whole blocks
            self.steps += 1; blk += 1
        if blk == len(self.bmin): return None
        for j in range(blk * self.b, min(self.n, (blk + 1) * self.b)):   # E moves by +-1: the first
            self.steps += 1                                              # block with min <= target has it
            if self.E[j] == target: return j
    def bwd(self, i, target):                          # largest j < i with E[j] == target; E[-1] = 0
        j = i - 1
        while j >= 0 and (j + 1) % self.b:             # the part of i's block before i
            self.steps += 1
            if self.E[j] == target: return j
            j -= 1
        blk = (j + 1) // self.b - 1                    # the block ending at j
        while blk >= 0 and self.bmin[blk] > target:    # skip whole blocks
            self.steps += 1; blk -= 1
        if blk < 0: return -1                          # only the virtual position -1 is left
        for j in range(min(self.n, (blk + 1) * self.b) - 1, blk * self.b - 1, -1):
            self.steps += 1
            if self.E[j] == target: return j
    def find_close(self, v): return self.fwd(v, self._exc(v) - 1)
    def parent(self, v):
        if v == 0: return None
        return self.bwd(v, self._exc(v) - 2) + 1
    def first_child(self, v): return v + 1 if self.bits[v + 1] else None
    def next_sibling(self, v):
        c = self.find_close(v) + 1
        return c if c < self.n and self.bits[c] else None
    def subtree_size(self, v): return (self.find_close(v) - v + 1) // 2
    def depth(self, v): return self.E[v]
    def preorder(self, v): return (v + self.E[v] - 1) // 2   # number of '(' before position v

def random_tree(n, rng):                               # parent array of a random ordinal tree, node 0 = root
    return [None] + [rng.randrange(i) for i in range(1, n)]

def to_bp(par):
    kids = [[] for _ in par]
    for v, p in enumerate(par):
        if p is not None: kids[p].append(v)
    bits, pos, stack = [], {}, [(0, False)]
    while stack:                                       # iterative DFS
        v, done = stack.pop()
        if done: bits.append(0); continue
        pos[v] = len(bits); bits.append(1)
        stack.append((v, True))
        for c in reversed(kids[v]): stack.append((c, False))
    return bits, pos, kids

rng = random.Random(1997)
par = random_tree(12, rng)
bits, pos, kids = to_bp(par)
print("12-node tree:", "".join("(" if x else ")" for x in bits))
t = BPTree(bits, b=4)
v = pos[kids[0][0]]
print(f"root's first child at position {v}: subtree size {t.subtree_size(v)}, parent {t.parent(v)}, next sibling {t.next_sibling(v)}")

n = 20000
par = random_tree(n, rng)
bits, pos, kids = to_bp(par)
t = BPTree(bits, b=32)
size = [1] * n
for v in range(n - 1, 0, -1): size[par[v]] += size[v]
depth = [1] * n
for v in range(1, n): depth[v] = depth[par[v]] + 1
order = sorted(range(n), key=lambda v: pos[v])
for v in rng.sample(range(n), 2000):
    p = pos[v]
    assert t.parent(p) == (pos[par[v]] if par[v] is not None else None)
    assert t.subtree_size(p) == size[v] and t.depth(p) == depth[v]
    assert order[t.preorder(p)] == v
print(f"n = {n}: 2000 random nodes, parent / subtree size / depth / preorder all correct")
print(f"space: {len(bits)} bits of parentheses + {len(t.bmin)} block minima of 15 bits ({len(t.bmin) * 15} bits); "
      f"a parent array needs {n * 15} bits")
print(f"average search steps per query: {t.steps / 4000:.1f}")
12-node tree: ((()(()))()(((()))()()))
root's first child at position 1: subtree size 4, parent 0, next sibling 9
n = 20000: 2000 random nodes, parent / subtree size / depth / preorder all correct
space: 40000 bits of parentheses + 1250 block minima of 15 bits (18750 bits); a parent array needs 300000 bits
average search steps per query: 8.5

Every answer agrees with the explicit tree. The parentheses take 2n2n bits, 7.5 times less than a parent array of 15-bit integers, and a parent array cannot even find children quickly. The program keeps the excess array explicitly for simplicity; a real implementation computes excesses on the fly from the bits with popcounts (rank) and stores only the small directory.

In C++

The same searches on a fixed 7-node tree, printing every node's depth, subtree size, parent, first child and next sibling, all derived from 14 bits.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <string>
#include <vector>

// Balanced-parentheses tree with block minima of the excess for forward and backward searches.
class BPTree {
    std::vector<int> E;                  // E[j] = excess of bits[0..j]
    std::vector<int> bmin;
    std::vector<bool> bits;
    int b, n;
    int exc(int j) const { return j < 0 ? 0 : E[j]; }
    int fwd(int i, int target) const {   // smallest j > i with E[j] == target, or -1
        int j = i + 1;
        for (; j < n && j % b; ++j) if (E[j] == target) return j;
        int blk = j / b;
        while (blk < static_cast<int>(bmin.size()) && bmin[blk] > target) ++blk;
        if (blk == static_cast<int>(bmin.size())) return -1;
        for (j = blk * b; j < std::min(n, (blk + 1) * b); ++j) if (E[j] == target) return j;
        return -1;
    }
    int bwd(int i, int target) const {   // largest j < i with E[j] == target; -1 is the virtual start
        int j = i - 1;
        for (; j >= 0 && (j + 1) % b; --j) if (E[j] == target) return j;
        int blk = (j + 1) / b - 1;
        while (blk >= 0 && bmin[blk] > target) --blk;
        if (blk < 0) return -1;
        for (j = std::min(n, (blk + 1) * b) - 1; j >= blk * b; --j) if (E[j] == target) return j;
        return -1;
    }
public:
    BPTree(const std::string& parens, int block) : b(block), n(static_cast<int>(parens.size())) {
        int e = 0;
        for (char c : parens) { bits.push_back(c == '('); e += c == '(' ? 1 : -1; E.push_back(e); }
        for (int i = 0; i < n; i += b) bmin.push_back(*std::min_element(E.begin() + i, E.begin() + std::min(n, i + b)));
    }
    int find_close(int v) const { return fwd(v, exc(v) - 1); }
    int parent(int v) const { return v == 0 ? -1 : bwd(v, exc(v) - 2) + 1; }
    int first_child(int v) const { return bits[v + 1] ? v + 1 : -1; }
    int next_sibling(int v) const { int c = find_close(v) + 1; return c < n && bits[c] ? c : -1; }
    int subtree_size(int v) const { return (find_close(v) - v + 1) / 2; }
    int depth(int v) const { return E[v]; }
    int preorder(int v) const { return (v + E[v] - 1) / 2; }
};

int main() {
    // Root r with children a and d; a has children b and c; d has child e, which has child f.
    std::string s = "((()())((())))";
    BPTree t(s, 4);
    const char* name = "rabcdef";                // node names in preorder
    std::printf("parentheses %s (%zu bits for 7 nodes)\n", s.c_str(), s.size());
    for (int v = 0; v < static_cast<int>(s.size()); ++v) {
        if (s[v] != '(') continue;
        int p = t.parent(v), c = t.first_child(v), sib = t.next_sibling(v);
        std::printf("%c at %2d: depth %d, subtree %d, parent %c, first child %c, next sibling %c\n",
                    name[t.preorder(v)], v, t.depth(v), t.subtree_size(v),
                    p < 0 ? '-' : name[t.preorder(p)], c < 0 ? '-' : name[t.preorder(c)],
                    sib < 0 ? '-' : name[t.preorder(sib)]);
    }
}
parentheses ((()())((()))) (14 bits for 7 nodes)
r at  0: depth 1, subtree 7, parent -, first child a, next sibling -
a at  1: depth 2, subtree 3, parent r, first child b, next sibling d
b at  2: depth 3, subtree 1, parent a, first child -, next sibling c
c at  4: depth 3, subtree 1, parent a, first child -, next sibling -
d at  7: depth 2, subtree 3, parent r, first child e, next sibling -
e at  8: depth 3, subtree 2, parent d, first child f, next sibling -
f at  9: depth 4, subtree 1, parent e, first child -, next sibling -

Constant time: the idea

The block scan costs O(b+n/b)O(b + n/b), O(n)O(\sqrt{n}) at best. Two refinements make it fast:

  • Range min-max trees (Sadakane and Navarro, 2010): a balanced tree over the blocks storing the minimum and maximum excess of each subtree. A search climbs and descends it, O(lg⁡n)O(\lg n) time in the simple version, and the same tree supports many more operations (level ancestors, ii-th child, lowest common ancestor). With a more careful multi-level design Sadakane and Navarro reach 2n+O(n/polylog⁡n)2n + O(n / \operatorname{polylog} n) bits and O(1)O(1) time for a long list of operations. This is what most libraries implement.
  • Munro and Raman's O(1)O(1) scheme (1997, 2001): most parentheses are matched within their own block of Θ(lg⁡n)\Theta(\lg n) bits, found by table lookup. The few "far" parentheses, whose matches lie in another block, are handled through pioneers: the first far parenthesis of each block with a match in a given other block. There are O(n/lg⁡n)O(n / \lg n) pioneers, and they form a balanced parentheses sequence of their own, recursively, so two levels of recursion and tables give FIND-CLOSE, FIND-OPEN and ENCLOSE in O(1)O(1) time with o(n)o(n) extra bits.

LOUDS in a few lines

The level-order unary degree sequence (Jacobson, 1989) is an even simpler 2n+12n + 1-bit encoding: write "10" for a virtual super-root, then visit the nodes in breadth-first order and write each node's number of children in unary (dd ones followed by a zero). Node ii in BFS order corresponds to the ii-th 1 bit, and navigation is pure rank and select: the children of node ii are written right after the ii-th 0, and the parent of node ii is the number of 0s before its 1 bit.

python · try it yourself
# LOUDS: visit nodes in BFS order and write each node's degree in unary (d ones, then a zero),
# after a "10" for a virtual super-root. Node i (BFS number, root = 1) is the i-th 1-bit.
children = {"r": ["a", "b", "c"], "a": ["d", "e"], "b": [], "c": ["f"], "d": [], "e": [], "f": []}
order, queue = [], ["r"]
while queue:
    v = queue.pop(0); order.append(v); queue += children[v]
bits = [1, 0]
for v in order:
    bits += [1] * len(children[v]) + [0]
print("BFS order:", " ".join(order), "| LOUDS:", "".join(map(str, bits)), f"({len(bits)} bits for {len(order)} nodes)")

def rank1(i): return sum(bits[:i])              # ones in bits[0..i-1] (O(1) with a directory)
def rank0(i): return i - rank1(i)
def select(bit, k):                             # position of the k-th bit equal to `bit`, k >= 1
    c = 0
    for p, b in enumerate(bits):
        c += b == bit
        if c == k: return p

def first_child(i):                             # node i -> BFS number of its first child, or None
    p = select(0, i) + 1                        # node i's degree starts after the i-th zero
    return rank1(p + 1) if bits[p] == 1 else None
def degree(i): return select(0, i + 1) - select(0, i) - 1
def parent(i):                                  # the node whose unary degree contains bit select1(i)
    return rank0(select(1, i))

for i, v in enumerate(order, 1):
    fc = first_child(i)
    print(f"{v}: degree {degree(i)}, first child {order[fc - 1] if fc else '-'}, parent {order[parent(i) - 1] if i > 1 else '-'}")
BFS order: r a b c d e f | LOUDS: 101110110010000 (15 bits for 7 nodes)
r: degree 3, first child a, parent -
a: degree 2, first child d, parent r
b: degree 0, first child -, parent r
c: degree 1, first child f, parent r
d: degree 0, first child -, parent a
e: degree 0, first child -, parent a
f: degree 0, first child -, parent c

LOUDS answers parent, first child, degree and ii-th child with O(1)O(1) rank and select operations, but not subtree size or depth, which need the depth-first structure of balanced parentheses.

Other succinct tree representations

Representation Bits Strengths
balanced parentheses (BP) 2n+o(n)2n + o(n) subtree size, depth, LCA, level ancestor
LOUDS (level-order unary degree sequence, Jacobson 1989): each node's degree in unary, in BFS order 2n+o(n)2n + o(n) parent and ii-th child by rank/select only; simple and fast
DFUDS (depth-first unary degree sequence, Benoit et al. 2005) 2n+o(n)2n + o(n) ii-th child and subtree size together
pointers Θ(nlg⁡n)\Theta(n \lg n) anything, with O(1)O(1) updates

All three succinct forms are static. Dynamic succinct trees exist (Navarro and Sadakane, 2014) with O(lg⁡n/lg⁡lg⁡n)O(\lg n / \lg \lg n) time per operation.

Test yourself

How many bits does the balanced-parentheses representation of an ordinal tree with nn nodes use, before the index?

  1. nn
  2. 2n2n
  3. nlg⁡nn \lg n
  4. 2nlg⁡n2n \lg n

In the parentheses (()(()))(()(())), the node at position 3 is the root's second child. What is FIND-CLOSE(3)(3), and so its subtree size?

  1. 6, size 2
  2. 4, size 1
  3. 7, size 3
  4. 5, size 2

Why is it enough to store the minimum excess of each block to skip blocks in FIND-CLOSE?

  1. Because blocks are small
  2. Because the excess changes by exactly ±1\pm 1 per position, so the first block whose minimum is at most the target contains the first position with that excess
  3. Because the tree is balanced
  4. Because the maximum is also stored