Editorial
The HTML representation can be constructed by following the definition with a DFS. However, the tree depth can be as large as , so an explicit stack avoids recursion-depth problems under the full constraints.
Store events in the stack. Let mean entering a node for the first time, and let mean leaving a tag node after all of its children have been processed.
When entering node , process it as follows.
- If it is a text node, append its string directly.
- If it is a tag node, append its opening tag, push , and then push its children in reverse order.
Because a stack processes the most recently pushed event first, pushing the children in reverse order makes the actual traversal follow the child order given in the input. When event is processed, append the closing tag.
Let be the sum of the numbers of nodes over all test cases and let be the total output length. Every node and every output character is processed only a constant number of times, so the time complexity is . The memory usage for one test case is .
Solution written by GPT5.6