Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python binary tree serializing problem

I have a binary tree class as below:

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

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

and I have another tree serializing method listed as below:

class JTree(object):
    def __init__(self, id, children=None): 
        self.id = id 
        if children is None:
            children=[]
        self.children = children

def encode_tree(obj):
    if not isinstance(obj, JTree):
        raise TypeError("%r is not JSON serializable" % (o,))

    return obj.__dict__

then I populate the Binary Tree data as below:

bt = BTree("1")
bt.left =BTree("2")
bt.right=BTree("3")

so if I serialize the data, I can get the following result:

tree = JTree(bt.data, [JTree(bt.left.data), JTree(bt.right.data)])

print json.dumps(tree, default=encode_tree)


{"id": "1", "children": [{"id": "2", "children": []}, {"id": "3", "children": []}]}

The problem is that I can't figure out how to program a piece of code to generate the result. Which means I want to have a generator or recursive function to run the code:

JTree(bt.data, [JTree(bt.left.data), JTree(bt.right.data)])

Can somebody give me an idea? Thanks

like image 241
georgehu Avatar asked Apr 27 '26 01:04

georgehu


1 Answers

It seems to me that you want a simple recursive function like:

def convert_to_jtree(bt):
    return JTree(bt.data, [convert_to_jtree(bt.left) if bt.left else None,
                          convert_to_jtree(bt.right) if bt.right else None])

or something very similar.

like image 152
Justin Peel Avatar answered Apr 28 '26 15:04

Justin Peel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!