【问题标题】:Python - Flatten a Tree which has N Children (N-ary tree)Python - 展平具有 N 个孩子的树(N-ary 树)
【发布时间】:2017-10-12 18:42:23
【问题描述】:

我想将一棵 N 叉树展平成这样的列表:

      P
______|______
|     |     |
C1    C2    C3         =>     [P,C1,C4,C2,C3,C5,C6]
|         ___|____
C4        |      |
         C5      C6

这是节点类:

class Node(object):
    def __init__(self, data):
        self.data = data
        self.children = []
    def add_child(self, obj):
        self.children.append(obj)

【问题讨论】:

  • 这不是简单的深度优先遍历吗?

标签: python tree flatten


【解决方案1】:
class Node(object):
    ...
    def flatten(self):
        return [self.data] + sum(
            (c.flatten() for c in self.children),
            [],
        )

不一定是最容易理解的,但我想尝试解决单线问题。

【讨论】:

    【解决方案2】:

    这就是我最终做的,它有效。

    class Node(object):
        def __init__(self, data):
            self.data = data
            self.children = []
        def add_child(self, obj):
            self.children.append(obj)
        def flatten(self):
            out = [self]
            for child in self.children:
                out += child.flatten()
            return out
    

    我尝试了一段时间来达到一个单一的解决方案,例如return [self] + [child.flatten() for child in self.children],但它从来没有工作过,因为它创建了嵌套列表。如果有人知道更整洁的方法,请分享。

    【讨论】:

    • 搜索“python扁平化列表”。
    猜你喜欢
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 2017-11-28
    • 1970-01-01
    相关资源
    最近更新 更多