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

发布于 2024-12-06 02:48:33 字数 494 浏览 0 评论 0原文

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

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

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

I have a binary tree class like this:

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

Now I'm facing a task to serialize this structure in to a nested list. BTW, I have a left-to-right traversal function in mind:

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

Or there is a general way to serialize it into mixed nested structure? For example, {[]}, or [{}]?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

白芷 2024-12-13 02:48:33

作为 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)

as a method of 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}

and as a class method of 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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文