我有一个像这样的二叉树类:
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
或者有一种将它序列化为混合嵌套结构的一般方法?例如,{[]}或[{}]?
答案 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)