Graph Theory37 sections · 1633 units
Open in Course

Path Queries II - Segment Tree

(Store values by position)

Build a segment tree of size nn. For each node vv, place val[v] at index pos[v] in the segment tree. This flattens the tree into a linear array. The segment tree supports update(p,x)update(p, x) to set position pp to value xx, and query(l,r)query(l, r) to return the maximum in range [l,r][l, r].

Both operations take O(logn)O(\log n) time. Initialize the segment tree with the initial node values. Each node's value goes at its flattened position. The segment tree maintains range maximums at internal nodes.

Space complexity is O(n)O(n) for the data structures used.