我做了两个类,如下所示:
- 节点类
class Node:
def __init__(self,title):
self.title = time
self.child = []
并实现getTitle、getChild、addChild、isEmpty等方法:if child=[]和更多
- 树类
class Tree:
def __init__(self, title):
self.root = Node('*')
self.wordset = set()
我想在Tree类中实现一个方法,这样我就可以制作Tree对象的等效列表结构(如下(
假设我有这样的树结构
a - p
/
* - t - o - y
p
甲酸obj:obj(title,[child](
假设我有如下的obj结构。。。
obj(*, [
obj(t, [
obj(o, [
obj(p, []),
obj(y, [])
]),
obj(a,[
obj(p, [])
])
])
])
我想在列表中使用这种结果obj结构
[t, [
[o, [
[p, []],
[y, []]
]
],
[a, [
[p, []]
]
]
]
]
详细信息。。。
我参考了这个问题并修改了代码,但输出并不像我在上写的那样
import Tree as tr
def getTree(obj):
inputList = obj.getChild()[:]
curResultList = []
stack = []
preResultList = []
while inputList or stack:
if inputList:
poppedObj = inputList.pop(0)
if poppedObj.isEmpty():
curResultList.append(poppedObj.getTitle())
else:
curResultList.append(poppedObj.getTitle())
stack.append((inputList, curResultList))
inputList = poppedObj.getChild()
curResultList = []
else:
inputList, preResultList = stack.pop()
preResultList.append(curResultList)
curResultList = preResultList
return curResultList
t = tr.Tree()
t.addWord('top')
t.addWord('toy')
t.addWord('tap')
print(t.getWordset())
print(getTree(t.root))
我的输出是:[not',['o',[p','y'],'a',[e'p']]
对我来说,他们在上面的函数或任何其他解决方案(递归或非递归(中是否有任何变化?
我认为您可以使用递归来简化这一点:
def getTree(obj):
return [
obj.getTitle(),
list(map(getTree, obj.getChild()))
]