Last active
May 1, 2018 16:07
-
-
Save huklee/8aa6abe646cb70ff15fffc993c85912a to your computer and use it in GitHub Desktop.
generateTree from a parsed Tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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