forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.py
31 lines (30 loc) · 949 Bytes
/
Solution.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# 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) -> TreeNode:
def dfs(s):
if not s:
return None
p = s.find('(')
if p == -1:
return TreeNode(int(s))
root = TreeNode(int(s[:p]))
start = p
cnt = 0
for i in range(p, len(s)):
if s[i] == '(':
cnt += 1
elif s[i] == ')':
cnt -= 1
if cnt == 0:
if start == p:
root.left = dfs(s[start + 1: i])
start = i + 1
else:
root.right = dfs(s[start + 1: i])
return root
return dfs(s)