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