The dictionary has key and value pairs of manager employee relationship, manager key can have multiple employees and those employees can have their own employees like below
data = {
"Amy": ["Alice", "Charlie"],
"Alice": ["Akon", "Eve"],
"Eve": ["Frank", None],
"Charlie": ["Bob", "Grace"]
}
while I can see all the nodes are getting added in the print statements below, but I am not able to print out the tree properly.
Here’s the code
class TreeNode:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def construct_binary_tree(data, root_key):
if root_key not in data:
return None
print("Constructing node:", root_key)
root = TreeNode(root_key)
if root_key in data:
children = data[root_key]
left_child_key = children[0] if children and len(children) > 0 else None
right_child_key = children[1] if children and len(children) > 1 else None
print("Left child of", root_key, ":", left_child_key)
print("Right child of", root_key, ":", right_child_key)
if left_child_key:
root.left = construct_binary_tree(data, left_child_key)
if right_child_key:
root.right = construct_binary_tree(data, right_child_key)
return root
def print_tree(root, depth=0):
if root:
print(" " * depth + f"|-- {root.key}")
print_tree(root.left, depth + 1)
print_tree(root.right, depth + 1)
# Given data
data = {
"Amy": ["Alice", "Charlie"],
"Alice": ["Akon", "Eve"],
"Eve": ["Frank", None],
"Charlie": ["Bob", "Grace"]
}
# Construct binary tree
root_key = next(iter(data))
root = construct_binary_tree(data, root_key)
# Print binary tree in tree format
print_tree(root)
Here’s the output I am seeing
Constructing node: Amy
Left child of Amy : Alice
Right child of Amy : Charlie
Constructing node: Alice
Left child of Alice : Akon
Right child of Alice : Eve
Constructing node: Eve
Left child of Eve : Frank
Right child of Eve : None
Constructing node: Charlie
Left child of Charlie : Bob
Right child of Charlie : Grace
|-- Amy
|-- Alice
|-- Eve
|-- Charlie