Tuple to display keys in a binary tree

Viewed 54

I want to create helper function to display all the keys in a tree-like structure for easier visualization.
Indeed, tuple's print is opaque.

My function should work like

tuple_to_display = ((1, 3, None)2,((None, 3, 4), 5,(6, 7, 8)))
display_keys(tuple_to_display)

display_keys in a command line should look like that:
How should look like

Could you tell me what I missed in the code below ?

class TreeNode:
    def __init__(self,key):
        self.key = key 
        self.left = None 
        self.right = None 
def parse_tuple(data):
    if isinstance(data,tuple) and len(data)==3:
        node = TreeNode(data[1])
        node.left= parse_tuple(data[0])
        node.right = parse_tuple(data[2])
    if data == None:
        node = None 
    else:
        node = TreeNode(data)
    return node 
def display_keys(node, space='\t', level=0):


    # print(node.key if node else None, level)
    
    # If the node is empty
    if node is None:
        print(space*level + '∅')
        return   
    
    # If the node is a leaf 
    if node.left is None and node.right is None:
        print(space*level + str(node.key))
        return
    
    # If the node has children
    display_keys(node.right, space, level+1)
    print(space*level + str(node.key))
    display_keys(node.left,space, level+1)  
tuple_to_display = ((1, 3, None), 2, ((None, 3, 4), 5,(6, 7, 8)))
tree2 = parse_tuple(tuple_to_display)#This is working 
print(display_keys(tree2, '  ')) #This give me none
1 Answers

The problem comes from parse_tuple(data): you should replace the second if by elif.

What you could also do is a return node after you first if. That should also work and maybe was your first intent.

Not doing either of the above means that what you return is TreeNode(data)

Next the fact that print(display_keys(tree2, ' ')) prints None is completely logical since the return type of the function has no return. The prints are handled inside the function.

By modifying the code accordingly->

...
def parse_tuple(data):
    if isinstance(data,tuple) and len(data)==3:
        node = TreeNode(data[1])
        node.left= parse_tuple(data[0])
        node.right = parse_tuple(data[2])
    elif data == None:
        node = None 
    else:
        node = TreeNode(data)
    return node 
 ...
 display_keys(tree2, '  ') 

I get

      8
    7
      6
  5
      4
    3
      ∅
2
    ∅
  3
    1
Related