#K76237. Mirror Binary Tree and Preorder Traversal
Mirror Binary Tree and Preorder Traversal
Mirror Binary Tree and Preorder Traversal
You are given a binary tree represented by a string in the format: node(left_subtree)(right_subtree)
. Node values can be negative. Your task is to convert the given binary tree into its mirror image and then output its pre-order traversal.
The mirror image of a binary tree is obtained by swapping the left and right children of every node. Formally, for a node \(r\), the mirror is defined as:
\( mirror(r) = swap( mirror(r.left), mirror(r.right) ) \)
with the base case \( mirror(null) = null \). For example, given the tree represented by 1(2(4)(5))(3(6)(7))
, its mirror image will have a pre-order traversal of 1 3 7 6 2 5 4
.
You are required to implement the following functions:
build_tree_from_string
: Parses the input string to construct the binary tree.mirror_tree
: Converts the binary tree to its mirror image.pre_order_traversal
: Outputs the pre-order traversal of the tree.handle_tests
: Reads multiple test cases from standard input, processes them, and prints the results.
</p>
inputFormat
The input consists of multiple test cases. The first line contains an integer (T), representing the number of test cases. Each of the following (T) lines contains a string representing a binary tree in parenthesis notation.
outputFormat
For each test case, output a single line containing the pre-order traversal of the mirrored binary tree, with node values separated by a single space.## sample
1
1
1