Skip to content

Instantly share code, notes, and snippets.

@huklee
Last active May 1, 2018 16:07
Show Gist options
  • Save huklee/8aa6abe646cb70ff15fffc993c85912a to your computer and use it in GitHub Desktop.
Save huklee/8aa6abe646cb70ff15fffc993c85912a to your computer and use it in GitHub Desktop.
generateTree from a parsed Tree
class Tree():
def __init__(self, val):
self.val = val
self.child = []
def addChild(self, t):
children = self.child
children.append(t)
def print(self, lev = ""):
print(lev + self.val)
for c in self.child:
c.print(lev + " ")
def solve(s):
st, last = [], None
for i in range(len(s)):
c = s[i]
# generate a new tree & push it into the stack
if c == "[":
t = Tree(s[i + 1])
if not st == []:
parent = st[-1]
parent.addChild(t)
st.append(t)
# pop the tree stack
elif c == "]":
last = st.pop()
return last
solve("[A[B[C][D[E[H]]]]]").print()
# Output
# A
# B
# C
# D
# E
# H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment