将二叉树结构编码为json格式

时间:2011-09-22 03:31:58

标签: python data-structures encoding binary-tree

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

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

    def __unicode__(self):
        return '%s' % self.data

我有这样的树遍历功能:

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

现在我陷入了生成像下面嵌套结构这样的数据格式:

{'id':1,children:[{'id':2, children:[{'id':3, 'id':4}]}]}

树结构是:

1

|

2

(left)3 (right)4

3 个答案:

答案 0 :(得分:4)

您需要做的是使您的类可序列化为字典和字符串的数据结构。我没有找到任何一般的方法,所以我通常做的是使BinaryTree实现某种或“flattening”和“解析”功能。这样做的一个好方法是:

import json

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

    def flatten(self):
        return {
            "data" : self.data, 
            "left" : self.left.flatten() if self.left else None,
            "right" : self.right.flatten() if self.right else None,
        }

    @classmethod
    def from_dictionary(cls, d):
        obj = cls(d["data"])

        if d.has_key("left") and d["left"] is not None:
            obj.left = cls.from_dictionary(d["left"])

        if d.has_key("right") and d["right"] is not None:
            obj.right = cls.from_dictionary(d["right"])

        return obj

if __name__ == "__main__":
    binary_tree = BinaryTree.from_dictionary({"data": "hello", "left": {"data" :  "yo"}})
    json_data = json.dumps(binary_tree.flatten())
    print "JSON: %s" % json_data
    binary_tree_from_json = BinaryTree.from_dictionary(json.loads(json_data))

    print binary_tree_from_json.data
    print binary_tree_from_json.left.data

答案 1 :(得分:2)

- 已编辑 -

您希望在每个节点中保留多少值?如果它只是一个int,如你的例子所示,它应该很容易:

节点具有id,一个或多个子节点以及值: { “1”:{“children”:[“2”],“value”:1111}, “2”:{“children”:[“3”,“4”],“value”:2222}, “3”:{“children”:null,“value”:3333}, “4”:{“children”:null,“value”:4444} }

答案 2 :(得分:0)

如果您熟悉堆栈,可以在下面看到代码。

"""
@param root: The root of binary tree.
@return: Preorder in list which contains node values.
"""
def preorderTraversal(self, root):
    if root is None:
        return []
    stack = [root]
    preorder = []
    while stack:
        node = stack.pop()
        preorder.append(node.val)
        if node.right:
            stack.append(node.right)
        if node.left:
            stack.append(node.left)
    return preorder