Binary Tree Implementation in Python

[1222 views]


A binary tree is a data structure of tree in which every node has at most two children, which are referred to as the left child and the right child.


Binary Tree implementation in Python

To implement a binary tree in python, we have to first define the Node class, which will represent a single node in the tree. Each node will have one left and one right node only:

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

Now we can start creating our tree:

root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7)
Full program :
class Node: def __init__(self, data): self.data = data self.left = None self.right = None def print_tree(root, space=0, t=0): COUNT = 3 if root is None: return space += COUNT print_tree(root.right, space, 1) for x in range(COUNT, space): print(" ",end = "") if t == 1 : # Right node print("/ ", root.data) elif t == 2 : # Left node print("\ ", root.data) else: # Root node print(root.data) #Process left child print_tree(root.left, space, 2) root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) print_tree(root)

You might be interested in this too.:

        

Algorithm Logic Test

Our Quiz prepared by Experts Helps you identify your knowledge in Algorithms. Everyone should atleast attempt this Quiz Once. 



Comments



Recommended Book Deals Ends in

Download 101 Ready to Use Excel Formulas ebook
Download Python All in One for Dummies ebook



Search
Online Games
Play 2048 Game Online and Relax.
Play 2048 Game Online

Search Tags

    Python Program for Binary Tree