![]() |
VOOZH | about |
Given a string s consisting of parentheses {'(' and ')'} and integers, the task is to construct a Binary Tree from it and print its Preorder traversal.
Examples:
Input: S = "1(2)(3)"
Output: 1 2 3
Explanation: The corresponding binary tree is as follows:
1
/ \
2 3Input: "4(2(3)(1))(6(5))"
Output: 4 2 3 1 6 5
Explanation:
The corresponding binary tree is as follows:4
/ \
2 6
/ \ /
3 1 5
Recursive Approach: Refer to the previous article to solve the problem recursively.
Time Complexity: O(N2)
Auxiliary Space: O(N)
Approach: This problem can be solved using stack data structure. Follow the steps below to solve the problem:
Below is the implementation of the above approach:
4 2 3 1 6 5
Time Complexity: O(N)
Auxiliary Space: O(N)