Editorial
If a vertex is chosen as the root, every neighbor of becomes a child of . Therefore, a vertex of degree at least cannot be chosen as the root of a binary tree.
Since the tree remains binary for every possible root, every vertex has degree at most . A connected tree whose vertices all have degree at most is a path.
List the vertices in order from one endpoint of this path. Let be the position of vertex . Let be the position of the current root, and let be the position of the queried vertex .
Build a Fenwick tree over this path order. Let denote the number of white vertices among the first positions.
If , the root lies to the right of . The subtree of is the interval , and the path from to the root is .
If , the root lies to the left of . The subtree of is the interval , and the path from to the root is .
If , vertex is the current root. Its subtree is the entire tree, while the path contains only .
A type 1 query only changes the stored root position. A type 2 query adds or at one Fenwick tree position. A type 3 query uses the formulas above.
Finding the path order takes time. Building the Fenwick tree takes time. Every query takes time, so the total time complexity is and the memory complexity is .
Solution written by GPT5.6