1

I have coded a binary tree structure in python. I could enter the data for each nodes but could not iterate it once insertion process is over (like in Java 12) and print it in the tree format.

class Tree:
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

def Insert(i, p):
    if i == 4:
        return
    else:
        p.left = Tree(input("Enter Value for left node\n"))
        p.right = Tree(input("Enter Value for right node\n"))
        Insert(i+1, p.left, )
        Insert(i+1, p.right, )

root = Tree(1)
Insert(0, root)
print(root)

When I print the root, I get its location in memory (something like:
<__main__.Tree object at 0x036D45D0>).

Is it possible to print all the values of the each node?

martineau
  • 119,623
  • 25
  • 170
  • 301
ganeshram
  • 127
  • 6

1 Answers1

2

The algorithm for printing a tree, in order, is actually quite simple. It's almost the same thing as what you're currently doing for insertion. Here's an example of an in-order traversal (the difference in ordering is whether print(root.data) goes before (preorder), between (in-order), or after (postorder) the recursive calls to its children).

def Print_Tree(root):
    if root is None:
        return
    Print_Tree(root.left)
    print(root.data)
    Print_Tree(root.right)
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53