3

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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This very cool! Thanks for solving my problem! A minor fix there is: convert_to_jtree(bt.left)
0

The json module can only serialize dicts, lists, strings, numbers, booleans and None. Instead of using custom classes for this, consider using plain-ol dicts. Alternately, you can subclass json.JsonEncoder and override the default method so that it returns one of those types for your custom class.

1 Comment

Actually it does. I just added json.dumps minute ago. Still, my question is, is there any way to run a code like this: JTree(bt.data, [JTree(bt.left.data), JTree(bt.right.data)])

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.