Construct Binary Tree from String Problem
Description
LeetCode Problem 536.
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]
Example 2:
Input: s = "4(2(3)(1))(6(5)(7))"
Output: [4,2,6,3,1,5,7]
Example 3:
Input: s = "-4(2(3)(1))(6(5)(7))"
Output: [-4,2,6,3,1,5,7]
Constraints:
0 <= s.length <= 3 * 10^4sconsists of digits,'(',')', and'-'only.- All numbers in the tree have value at most than
2^30.
Solution
Approach: One Pass with a Stack
Read the string from left to right and keep a stack of the nodes whose parentheses are still open. The stack is the path from the root down to the node whose children we are currently reading.
There are only three kinds of tokens:
- A number (possibly with a leading
-): create a node. If the stack is empty, it is the root. Otherwise it is a child of the node on top of the stack: the left child if that node has none yet, else the right child. Then push the new node, since its own children may follow. (: starts a child subtree. Nothing to do; the number right after it will be attached to the top of the stack.): the subtree whose root is on top of the stack is complete, so pop it.
Take "4(2(3)(1))(6(5))": 4 becomes the root; 2 is its left child; 3 is the left and 1 the right child of 2; after the ) that closes 2, the top is 4 again, so 6 becomes its right child, and 5 the left child of 6.
Two details: a number can be several digits long and may start with -, so read the whole number at once; and the empty string means an empty tree, so return null. Using a stack instead of recursion also keeps the work safe for very deep trees, such as a long chain of left children.
Complexity: O(n) time, where n is the length of s: each character is read once. O(h) extra space for the stack, where h is the height of the tree.
class Solution:
def str2tree(self, s: str) -> Optional[TreeNode]:
stack = [] # the path from the root to the node whose children we are reading
root = None
i = 0
while i < len(s):
if s[i] == ")":
stack.pop() # this subtree is complete
i += 1
elif s[i] == "(":
i += 1
else:
j = i + 1
while j < len(s) and s[j].isdigit():
j += 1
node = TreeNode(int(s[i:j]))
if not stack:
root = node
elif stack[-1].left is None:
stack[-1].left = node # the first child is always the left one
else:
stack[-1].right = node
stack.append(node)
i = j
return root