Build a segment tree of size . For each node , place val[v] at index pos[v] in the segment tree. This flattens the tree into a linear array. The segment tree supports to set position to value , and to return the maximum in range .
Both operations take 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 for the data structures used.