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.
The string encodes a binary tree using integers and parentheses. We can recursively parse the string, always building the left child first, then the right child, as per the problem statement. The recursion naturally matches the parenthesis structure.
dataclassTreeNode(var `val`: Int, var left: TreeNode? = null, var right: TreeNode? = null)
classSolution {
funstr2tree(s: String): TreeNode? {
var i = 0funparse(): TreeNode? {
if (i >= s.length) returnnullvar sign = 1; var num = 0if (s[i] =='-') { sign = -1; i++ }
while (i < s.length && s[i].isDigit()) num = num * 10 + (s[i++] - '0')
val node = TreeNode(sign * num)
if (i < s.length && s[i] =='(') {
i++ node.left = parse()
i++ }
if (i < s.length && s[i] =='(') {
i++ node.right = parse()
i++ }
return node
}
return parse()
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classTreeNode:
def__init__(self, val: int, left: 'TreeNode'=None, right: 'TreeNode'=None):
self.val = val
self.left = left
self.right = right
classSolution:
defstr2tree(self, s: str) ->'TreeNode | None':
defparse(i: int) -> tuple['TreeNode | None', int]:
if i >= len(s): returnNone, i
sign, num =1, 0if s[i] =='-': sign, i =-1, i+1while i < len(s) and s[i].isdigit():
num = num *10+ int(s[i]); i +=1 node = TreeNode(sign * num)
if i < len(s) and s[i] =='(': left, i = parse(i+1); node.left = left; i +=1if i < len(s) and s[i] =='(': right, i = parse(i+1); node.right = right; i +=1return node, i
node, _ = parse(0)
return node