536. Construct Binary Tree from String
recursive, double return
Input: s = "4(2(3)(1))(6(5))"
Output: [4,2,6,3,1,5]Input: s = "4(2(3)(1))(6(5)(7))"
Output: [4,2,6,3,1,5,7]Input: s = "-4(2(3)(1))(6(5)(7))"
Output: [-4,2,6,3,1,5,7]Last updated
recursive, double return
Input: s = "4(2(3)(1))(6(5))"
Output: [4,2,6,3,1,5]Input: s = "4(2(3)(1))(6(5)(7))"
Output: [4,2,6,3,1,5,7]Input: s = "-4(2(3)(1))(6(5)(7))"
Output: [-4,2,6,3,1,5,7]Last updated
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def str2tree(self, s: str) -> Optional[TreeNode]:
n = len(s)
def helper(s, index):
if index >= len(s) or s[index] == ')':
return None, index
sign = 1
if s[index] == '-':
sign = -1
index += 1
num = 0
while index < len(s) and s[index].isdigit():
num = num*10 + int(s[index])
index += 1
num = sign*num
root = TreeNode(num)
if index < n and s[index] == '(':
root.left, index = helper(s, index+1)
if root.left and index < n and s[index] == '(':
root.right, index = helper(s, index+1)
if index < len(s) and s[index] == ')':
index += 1
return root, index
if not s:
return None
return helper(s,0)[0]