A binary tree is a hierarchical data structure which has at most two child nodes, i.e no node in the tree can have a degree greater than two. For a binary tree, we distinguish between the subtree on the left and right as left subtree and right subtree respectively.
In the previous tutorial, we went through file handling in python and in this tutorial we are going to implement Tree Data Structure in Python. So let’s get started.
We represent a Binary Tree by a pointer to the topmost node in tree. If the tree is empty, then value of root is NULL.
A Tree node contains following parts:
Let’s see an example by implementing this Node:
class Node:
def __init__(self, val):
self.right = None
self.left = None
self.data = val
Let’s analyze this code snippet before we go ahead.
Now we need methods to check if the childs are empty or not:
class Node:
def __init__(self, val):
self.right = None
self.left = None
self.data = val
def is_empty_lchild(self):
if self.left == None:
return True
return False
def is_empty_rchild(self):
if self.right == None:
return True
return False
Now that we have finalized the ingredients let’s finalize the recipe.
class Node:
def __init__(self, val):
self.right = None
self.left = None
self.data = val
def is_empty_lchild(self):
if self.left == None:
return True
return False
def is_empty_rchild(self):
if self.right == None:
return True
return False
vals = [x for x in range(1, 10)]
# setting root code
root = Node(0)
x = root
for i in vals:
if x.is_empty_lchild():
x.left = Node(i)
print('left')
elif x.is_empty_rchild():
x.right = Node(i)
print('right')
x = x.left
Checking Our Code:
>>>root.data
Out[16]: 0
>>>root.left.data
Out[17]: 1
>>>root.right.data
Out[18]: 2
>>>root.left.left.data
Out[19]: 3
>>>root.left.right.data
Out[20]: 4
In Python, the print() function is a fundamental tool for displaying output. While printing simple…
Python is a versatile programming language known for its simplicity and flexibility. When working on…
PDF (Portable Document Format) files are commonly used for sharing documents due to their consistent…
PDF (Portable Document Format) files are widely used for document exchange due to their consistent…
Python is a high-level programming language known for its simplicity and ease of use. However,…
Object-Oriented Programming (OOP), iterators, generators, and closures are powerful concepts in Python that can be…
This website uses cookies.