How can I build a binary tree given a nested dictionary? Ideally, I want access to the root to then traverse the tree in a regular depth-first or breadth-first fashion.
I am not super concerned with efficiency when building the tree from the nested dictionary in terms of time or space so I don't mind using additional data structures in the process. My main focus is a comprehensive and intuitive solution. I have no idea where to start at the moment so any help is greatly appreciated.
class Vertex:
"""Vertex object in a binary tree."""
def __init__(self):
"""Initialize Vertex object.
Fields
----------
value : int
The value of node v
left : None
The left child of node v
right : None
The right child of node v
"""
self.value = None
self.left = None
self.right = None
def dict_to_binary_tree(data):
"""Implementation here."""
return root
if __name__ == '__main__':
t = {
"value": 1,
"left": {
"value": 2,
"left": {
"value": 3,
"left": None,
"right": None
},
"right": {
"value": 4,
"left": None,
"right": None
}
},
"right": {
"value": 2,
"left": {
"value": 4,
"left": None,
"right": None
},
"right": {
"value": 3,
"left": None,
"right": None
}
}
}
root = dict_to_binary_tree(t)
# traverse tree i.e. dfs(root), bfs(root)
Here is what the binary tree looks like:
1
/ \
2 2
/ \ / \
3 4 4 3