用Python展平树

时间:2018-11-23 12:01:27

标签: python tree extract

我有这棵树,我想按顺序压扁树(不区分大小写),我创建了extract_nodes_containing_string来提取叶子,但是以下代码不起作用:

class Node(object):
    def __init__(self, name, children=None):
        self.name = name
        self.children = children or []

    def __repr__(self):
        return '<Node name={}>'.format(self.name)

    def extract_nodes_containing_string(self, needle):
        # TODO: Please implement me
        # needs to be case insensitive
        if needle is None: return needle
        self.getflatten(needle)

    def getflatten(self, root):
        if root is None: return
        self.getflatten(root.left)
        self.getflatten(root.right)
        current = root.left
        if current is None: return
        while current.right is not None:
            current = current.right
        current.right = root.right
        root.right = root.left
        root.left = None


# Example:

def create_tree():
    return Node('root', [
        Node("MaGaZiNo", [
            Node("I"),
            Node("Love"),
            Node("magazino")
        ]),
        Node("Hello", [
            Node("Hello", [
                Node("Hello", [
                    Node("World")
                ])
            ])
        ])
    ])


root = create_tree()
print(root.extract_nodes_containing_string('root') == [root])

如果有人能帮助我,那太好了。

0 个答案:

没有答案