Graph Theory37 sections · 1633 units
Open in Course

Flattening the Tree

(Building the array)

Create an array arr where arr[tin[v]] holds node vv's value. Run DFS, assign entry times, and place values in the array.

Now you have a flat array. The subtree of vv corresponds to range [tin[v], tout[v]] in this array. Any range data structure (segment tree, BIT) can now handle subtree queries. This converts tree problems into array problems you already know how to solve. The flattening step is O(n)O(n) and only needs to be done once.