Reputation: 3
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]
Upvotes: 0
Views: 144
Reputation: 54698
The data structure they gave you is a perfectly fine way to store a binary tree. There's no particular need to convert it to objects. You could have a Tree
object and have these all be methods of that class, but I'm not sure that's really better.
from collections import defaultdict
tree = {6:(None,None), 10:(2,6), 2:(None,None), 3:(14,None),8:(10,3)}
def find_root(tree):
nodes = defaultdict(int)
for k,(l,r) in tree.items():
if l:
nodes[l] += 1
if r:
nodes[r] += 1
for k in tree:
if k not in nodes:
return k
def pre_traverse(tree,node):
if not node:
return
print(node)
if not node in tree:
return
pre_traverse(tree,tree[node][0])
pre_traverse(tree,tree[node][1])
def in_traverse(tree,node):
if not node:
return
if not node in tree:
print(node)
return
in_traverse(tree,tree[node][0])
print(node)
in_traverse(tree,tree[node][1])
root = find_root(tree)
print("in-order traversal:")
in_traverse(tree,root)
print("pre-order traversal:")
pre_traverse(tree,root)
Output:
in-order traversal:
2
10
6
8
14
3
pre-order traversal:
8
10
2
6
3
14
Upvotes: 0