Python program to find Height of a complete binary tree (or Heap) with N nodes
In this tutorial, we’ll be seeing how to find the height of a complete binary tree with n nodes in Python.
Before seeing the code let’s first discuss what’s exactly the height of a binary tree is. The height of a binary tree is nothing but the distance between the first node of the tree to the last bottom node.
The function is a recursive function, The steps are as follows:
- We check whether the node is empty or not. If it is we return 0.
- We then find call the function to find the height of the left part of the binary tree.
- Then we find the height of the right part of the binary tree.
- Compare the 2 heights and whichever height is more we return that height +1 to count the current node.
- This is a recursive function so most of the computing is done by the computer itself.
This is how we find the height of the binary tree.
This is a code snippet in python on how to find the height of a binary tree with time complexity O(n).
The following code helps us find the height of a binary tree:-
class Node:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
def height(no):
if no is None:
return 0
else:
ld=height(no.left)
rd=height(no.right)
if(ld>rd):
return ld+1
else:
return rd+1
root=Node(1)
root.left=Node(2)
root.right=Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print(height(root))
Leave a Reply