Parenthesized string to tree
Question:
I am trying to transform this string:
function1(function2(a, b), c)
to a tree-like structure:
function1
|-function2
|--a
|--b
|-c
I tried with recursive function, but I can’t find a solution to this problem.
Answers:
Here is a recursive function creating a tree from a string:
treeTest = "A(a, b(c, d),B,C(a,b))"
class node():#Node class for trees
def __init__(self, value):
self.value = value
self.children = []
def __repr__(self):
return self.value
def treeGenerator(tree : str) -> node: #Will return with a tree
Node = node("Root")
tree = list(tree)
def makeTree(root):
currentNode = None
while tree:
letter = tree.pop(0)
if letter.isalpha():
currentNode = node(letter)
root.children.append(currentNode)
elif letter == "(":
makeTree(root.children[-1])
elif letter == ")":
return
makeTree(Node)
return Node.children[0]
treeGenerator(treeTest)
I am trying to transform this string:
function1(function2(a, b), c)
to a tree-like structure:
function1
|-function2
|--a
|--b
|-c
I tried with recursive function, but I can’t find a solution to this problem.
Here is a recursive function creating a tree from a string:
treeTest = "A(a, b(c, d),B,C(a,b))"
class node():#Node class for trees
def __init__(self, value):
self.value = value
self.children = []
def __repr__(self):
return self.value
def treeGenerator(tree : str) -> node: #Will return with a tree
Node = node("Root")
tree = list(tree)
def makeTree(root):
currentNode = None
while tree:
letter = tree.pop(0)
if letter.isalpha():
currentNode = node(letter)
root.children.append(currentNode)
elif letter == "(":
makeTree(root.children[-1])
elif letter == ")":
return
makeTree(Node)
return Node.children[0]
treeGenerator(treeTest)