I have a dictionary of nodes and their children but I am stuck at inserting the children's nodes to construct a binary tree. I am using the binary tree to get the preorder traversal and inorder traversal.
input: Each key pair represent: root:(left child, right child) and can be in any order {6:(None,None), 10:(2,6), 2:(None,None), 3:(14,None),8:(10,3)}
Output Tree
I wanted the tree to be in class format (e.g. root.left will return 10, root.left.right will return 6. But my code is not looking for the root node which should be 8:(10,3) and collect all children. How can i enhance the code?
class Node:
def __init__(self, key, left, right):
self.key= key
self.left = left
self.right = right
# Compare the new key with the left and right node
def insert(self, key, vals):
if self.key == None:
self.key = key
self.left = vals[0]
self.right = vals[1]
# else if left is equal to key
elif self.left == key:
self.key = key
self.left = vals[0]
self.right = vals[1]
# else if right is equal to key
elif:
self.key = key
self.left = vals[0]
self.right = vals[1]
Nodeclass and will be separate.insert. You don't ever change the existing key. Instead, you create a NEWNodeand find a place for it, either as the new root or at another location.