fork download
  1. s = "A(BB(CC))"
  2. # 012345678
  3.  
  4.  
  5. def build_tree(s, root = {"children": [], "l": 0}, i = 0, j = 0):
  6. if i == len(s):
  7. return (root, i)
  8.  
  9. if s[i] == ")":
  10. root["r"] = j #root["l"] + 2 * (j - root["l"] + 1)
  11. return (root, i + 1)
  12.  
  13. cs = root["children"]
  14.  
  15. if s[i] == "(":
  16. if cs and isinstance(cs[-1], list):
  17. cs[-1][1] = i - 1
  18. cs[-1][3] = j
  19. child, ii = build_tree(s, {"children": [], "l": j}, i+1, j)
  20. root["r"] = child["r"]
  21. root["children"].append(child)
  22. return build_tree(s, root, ii, root["r"] + 1)
  23.  
  24. if not cs or not isinstance(cs[-1], list):
  25. root["children"].append([i, None, j, None])
  26.  
  27. root["r"] = j
  28. return build_tree(s, root, i + 1, j + 1)
  29.  
  30.  
  31. print(build_tree(s))
Success #stdin #stdout 0.04s 9600KB
stdin
Standard input is empty
stdout
({'children': [[0, 0, 0, 1], {'children': [[2, 3, 1, 3], {'children': [[5, None, 3, None]], 'l': 3, 'r': 5}], 'l': 1, 'r': 6}], 'l': 0, 'r': 6}, 9)