453. Construct Binary Tree from String

You need to construct a binary tree from a string consisting of parenthesis and integers.

The whole input represents a binary tree. It contains an integer followed by zero, one or two pairs of parenthesis. The integer represents the root's value and a pair of parenthesis contains a child binary tree with the same structure.

You always start to construct the left child node of the parent first if it exists.

Example 1:

Input: s = "4(2(3)(1))(6(5))"

Output: [4,2,6,3,1,5]

Explanation:

Here, the root of the binary tree is 4. The left subtree is represented by "2(3)(1)", meaning 2 is the left child of 4, 3 is the left child of 2, and 1 is the right child of 2. The right subtree is "6(5)", meaning 6 is the right child of 4 and 5 is the left child of 6. The final level-order traversal of this tree results in [4,2,6,3,1,5].

Example 2:

Input: s = "4(2(3)(1))(6(5)(7))"

Output: [4,2,6,3,1,5,7]

Explanation:

Similar to the previous case, the root is 4. The left subtree "2(3)(1)" forms the same structure as before. However, the right subtree "6(5)(7)" now includes an additional right child 7 for node 6. The level-order traversal of this tree gives [4,2,6,3,1,5,7].

Now Your Turn!

Pick the correct output for the given input

Input: s = "1(2(6(7(9)))(3(5)))(4(8))"

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 0 <= s.length <= 3 * 104
  • s consists of digits, '(', ')', and '-' only.
  • All numbers in the tree have value at most than 230.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* str2tree(string s) {
// Your code goes here
}
};
Test Case

Input:

S