将 n 个子树的对象结构转换为 python 中的嵌套列表

convert object structure of n child tree to nested list in python

我做了两个class如下:

  1. 节点class
class Node:
    def __init__(self,title):
        self.title = time
        self.child = []

并实现 getTitle、getChild、addChild、isEmpty 等方法:if child = [] 等

  1. 树class
class Tree:
    def __init__(self, title):
        self.root = Node('*')
        self.wordset = set()

我想在 Tree 中实现一个方法 class ,这样我就可以做一个 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, [])
                       ])
               ])
       ])

我想要列表中的这种结果对象结构

[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))

我的输出是:['t'、['o'、['p'、'y']、'a'、['p'] ]]

上面的函数或任何其他解决方案(递归或非递归)是否对我提出了任何更改建议?

我认为你可以使用递归来简化它:

def getTree(obj):
    return [
        obj.getTitle(),
        list(map(getTree, obj.getChild()))
    ]