使用继承返回树列表

时间:2019-12-08 19:36:26

标签: python inheritance tree

树(例如继承树)是数据结构 与父节点和子节点。例如

               A
              /  |
             B     C
            / |     |
           D   E     F

我们将树表示为一棵以节点名称为键的字典,然后 子名称值列表。

{"A":["B", "C"], "B":["D","E"], "C":["F"], "D":[], "E":[], "F":[]}

考虑每个有序列表,并使用递归遍历该列表 “深度优先”。

按深度优先遍历过程中的访问顺序返回字母字符串。 对于此示例,系统应返回“ ABDECF”

:param parent: current node being processed
:param tree: dictionary of the entire tree - do not modify this in recursive call
:return: String representing depth first traversal

我非常了解继承,在这种情况下,我只是不了解我应该怎么做。任何帮助将不胜感激。

class Program4:
    def __init__(self):
        self.counter=0

    def traverse(self, parent, tree):
        self.counter += 1 # Leave this counter alone

        #@todo - fix this.
        #   call recursion with self since instance method
        #  This is doable in no more than six lines of code

        pass

if __name__ == "__main__":
    tree = {"A":["B", "C"], "B":["D","E"], "C":["F"], "D":[], "E":[], "F":[]}

    print("Tree:",tree)
    p=Program4()
    print("Depth first:",p.traverse("A",tree))

1 个答案:

答案 0 :(得分:1)

将执行以下操作:

class Program4:
    # ...
    def traverse(self, parent, tree):
        # ...
        s = parent
        for child in tree.get(parent, []):
            s += self.traverse(child, tree)
        return s

基本案例是没有子节点的叶节点,在这种情况下(您可以验证),返回了父节点本身。在所有其他情况下,父级子树的遍历都将附加到它。

您可以使用str.join和生成器以单线的方式进行操作:

# ...
def traverse(self, parent, tree):
    return parent + ''.join(self.traverse(c, tree) for c in tree.get(parent, []))

>>> p = Program4()
>>> print("Depth first:", p.traverse("A", tree))
Depth first: ABDECF