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))