使用python将Tree序列化为嵌套列表

时间:2011-09-23 01:06:44

标签: serialization tree nested

我有一个像这样的二叉树类:

class BinaryTree:
def __init__(self, data, left=None, right=None):
    self.data = data
    self.left = left
    self.right = right

现在,我正面临着将此结构序列化为嵌套列表的任务。顺便说一句,我有一个从左到右的遍历功能:

def binary_tree(tree):
    if tree:
        for node_data in binary_tree(tree.left):
            yield node_data
        for node_data in binary_tree(tree.right):
            yield node_data

或者有一种将它序列化为混合嵌套结构的一般方法?例如,{[]}或[{}]?

1 个答案:

答案 0 :(得分:0)

作为BinaryTree的方法:

def to_dict(self):
    data = self.data
    left = self.left
    if left is not None:
        left = left.to_dict()
    right = self.right
    if right is not None:
        right = right.to_dict()
    return {'data':data, 'left':left, 'right':right}

并作为BinaryTree的类方法:

def from_dict(cls, D):
    data = D['data']
    left = D['left']
    if left is not None:
        left = cls.from_dict(left)
    right = D['right']
    if right is not None:
        right = cls.from_dict(right)
    return cls(data, left, right)