You are given a string ‘str’ which consists of brackets and integers ∈ [1, 9]. Your task is to construct a binary tree from the given string and return the Pre-Order Traversal of it.
The rules are as follows
1. The first character of the string is guaranteed to be an integer which denotes the root element of the tree.
2. This is followed by zero, one or two pairs of parenthesis, which contains a child binary tree with the same structure.
3. The first parenthesis denotes the left child of the binary then the right child.
For Example
Let str= “1(2)(3)”
The tree will be:

The first element i.e 1 is the root node and the first bracket signifies the left child of the root node which has only 1 element i.e 2 and the second bracket signifies the right child of the root node that has only 1 node i.e 3 . Hence we have the binary tree as shown above.
The first line of input contains an integer ‘T’ denoting the number of test cases to run. Then the test cases follow.
The first line of each test case contains the string ‘str’.
Output Format
For each test case, return the root node of the constructed binary tree.
The printed output is the preorder traversal of the binary tree.
Output for each test case will be printed in a new line.
Note
You do not need to print anything; it has already been taken care of. Just implement the given function.
1 <= T <= 5
1 <= N <= 1000
Where 'N' denotes the length of the string 'str'
Time limit: 1 second
2
4(2(3)(1))(6(5))
4(2(3(1)))(5)
4 2 3 1 6 5
4 2 3 1 5
Test Case 1:
In the first test case,
We will have the following binary tree:

Test Case 2:
In the second first case we will have the following tree:

1
1(2(4)(5))(3(6)(7))
1 2 4 5 3 6 7
The key idea in solving this problem is to construct the tree recursively and then print the pre-order traversal.
Algorithm
O(N^2), where ‘N’ is the length of the string str .
In the worst case we can have one node in each level and the find ‘index’ is a linear function which can be called atmost ‘n’ times for making the tree. Thus overall complexity can be O(N^2)
O(N), where N is the length of ‘str’.
The space complexity due to the recursion stack will be O(N).