s = "A(BB(CC))"
# 012345678
def build_tree(s, root = {"children": [], "l": 0}, i = 0, j = 0):
if i == len(s):
return (root, i)
if s[i] == ")":
root["r"] = j #root["l"] + 2 * (j - root["l"] + 1)
return (root, i + 1)
cs = root["children"]
if s[i] == "(":
if cs and isinstance(cs[-1], list):
cs[-1][1] = i - 1
cs[-1][3] = j
child, ii = build_tree(s, {"children": [], "l": j}, i+1, j)
root["r"] = child["r"]
root["children"].append(child)
return build_tree(s, root, ii, root["r"] + 1)
if not cs or not isinstance(cs[-1], list):
root["children"].append([i, None, j, None])
root["r"] = j
return build_tree(s, root, i + 1, j + 1)
import json
print(json.dumps(build_tree(s)[0], indent=2))
cyA9ICJBKEJCKENDKSkiCiMgICAgMDEyMzQ1Njc4CgoKZGVmIGJ1aWxkX3RyZWUocywgcm9vdCA9IHsiY2hpbGRyZW4iOiBbXSwgImwiOiAwfSwgaSA9IDAsIGogPSAwKToKICBpZiBpID09IGxlbihzKToKICAgIHJldHVybiAocm9vdCwgaSkKCiAgaWYgc1tpXSA9PSAiKSI6CiAgICByb290WyJyIl0gPSBqICNyb290WyJsIl0gKyAyICogKGogLSByb290WyJsIl0gKyAxKQogICAgcmV0dXJuIChyb290LCBpICsgMSkKCiAgY3MgPSByb290WyJjaGlsZHJlbiJdCgogIGlmIHNbaV0gPT0gIigiOgogICAgaWYgY3MgYW5kIGlzaW5zdGFuY2UoY3NbLTFdLCBsaXN0KToKICAgICAgY3NbLTFdWzFdID0gaSAtIDEKICAgICAgY3NbLTFdWzNdID0gagogICAgY2hpbGQsIGlpID0gYnVpbGRfdHJlZShzLCB7ImNoaWxkcmVuIjogW10sICJsIjogan0sIGkrMSwgaikKICAgIHJvb3RbInIiXSA9IGNoaWxkWyJyIl0KICAgIHJvb3RbImNoaWxkcmVuIl0uYXBwZW5kKGNoaWxkKQogICAgcmV0dXJuIGJ1aWxkX3RyZWUocywgcm9vdCwgaWksIHJvb3RbInIiXSArIDEpCgogIGlmIG5vdCBjcyBvciBub3QgaXNpbnN0YW5jZShjc1stMV0sIGxpc3QpOgogICAgcm9vdFsiY2hpbGRyZW4iXS5hcHBlbmQoW2ksIE5vbmUsIGosIE5vbmVdKQoKICByb290WyJyIl0gPSBqCiAgcmV0dXJuIGJ1aWxkX3RyZWUocywgcm9vdCwgaSArIDEsIGogKyAxKQoKCmltcG9ydCBqc29uCgpwcmludChqc29uLmR1bXBzKGJ1aWxkX3RyZWUocylbMF0sIGluZGVudD0yKSk=
{
"children": [
[
0,
0,
0,
1
],
{
"children": [
[
2,
3,
1,
3
],
{
"children": [
[
5,
null,
3,
null
]
],
"l": 3,
"r": 5
}
],
"l": 1,
"r": 6
}
],
"l": 0,
"r": 6
}