Skip to content

Instantly share code, notes, and snippets.

@zh4ngx
Created October 10, 2013 02:42
Show Gist options
  • Save zh4ngx/6912207 to your computer and use it in GitHub Desktop.
Save zh4ngx/6912207 to your computer and use it in GitHub Desktop.
Function to marshal binary tree (represented as dict). Done kind of in a hurry (like 20m)....
# Arbitary binary tree (integers)
### 1
### 2 3
### 6 4 5
## {1:{"left":2,"right":{3:{"left":4,"right":5}}}}
## Goal: -> '{1:{left:2,right:{3:{left:4,right:5}}}}'
# 1
# 2 3
## '{1:{left:2,right:3}}'
tree_string = ""
def marshal(tree):
# if has children
if tree.get('left') or tree.get('right'):
tree_string.append("{" + str(tree.root) + ":{")
if tree.get('left'):
tree_string.append("left": marshal(tree['left']))
if tree.get('right'):
if tree.left:
tree_string.append(",")
tree_string.append("right": marshal(tree['right']))
# close inner tree
tree_string.append("}")
# if leaf
else:
tree_string.append(':' + str(tree.root))
# close outer tree
tree_string.append("}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment