# Binary tree node class node: def __init__(self, data): self.left=None self.right=None self.data=data # Function to create a new # Binary node def newNode(data): return node(data) def t(): root=newNode("A") root.left = newNode("B") root.right = newNode("C") root.left.left = newNode("D") root.left.right = newNode("G") root.right.right = newNode("E") root.right.right.left = newNode("F") print(t)
Hi, I have tried to create a Binary Tree above but I did not managed to print out the binary tree when I print “t”. Instead of a Binary Tree, it shows me this:
Advertisement
Answer
Function t
just creates a binary tree. If you want to print a tree you need to traverse it and print it. Depending on the way you want to print a tree, there are different traversal techniques, the popular of which are Inorder
, Preorder
and Postorder
. Check this wiki link for tree traversal methods.
Your code has to be extended to do the required tree traversal. Sample is below:
# Binary tree node class node: def __init__(self, data): self.left=None self.right=None self.data=data # Function to create a new # Binary node def newNode(data): return node(data) def t(): root=newNode("A") root.left = newNode("B") root.right = newNode("C") root.left.left = newNode("D") root.left.right = newNode("G") root.right.right = newNode("E") root.right.right.left = newNode("F") return root def in_order(root): if root: in_order(root.left) print (root.data) in_order(root.right) def pre_order(root): if root: print (root.data) pre_order(root.left) pre_order(root.right) def post_order(root): if root: post_order(root.left) post_order(root.right) print (root.data) root = t() print ("In Order") in_order(root) print ("Pre Order") pre_order(root) print ("Post Order") post_order(root)
Output:
In Order D B G A C F E Pre Order A B D G C E F Post Order D G B F E C A