Python Program to Find the Height of a Binary Tree

This program calculates the height of a binary tree. The height is defined as the number of edges on the longest downward path between the root and a leaf. A recursive function is used to explore each subtree and determine the maximum depth.


class TreeNode:
    """Definition of a binary tree node."""
    def __init__(self, x):
        """
        Initialize a tree node with a value.
        
        :param x: int, the integer value of the node
        """
        self.val = x
        self.left = None
        self.right = None

def height(root):
    """
    Calculate the height of the binary tree.

    :param root: TreeNode, the root of the binary tree
    :return: int, the height of the tree measured in number of edges
    """
    if root is None:
        return -1  # base case: height of an empty tree is -1
    else:
        # recursive case: 1 + maximum of the height of the left and right subtrees
        return 1 + max(height(root.left), height(root.right))

# Example Usage
if __name__ == "__main__":
    # Construct a simple tree
    root = TreeNode(1)
    root.left = TreeNode(2)
    root.right = TreeNode(3)
    root.left.left = TreeNode(4)
    root.left.right = TreeNode(5)

    # Calculate the height of the tree
    tree_height = height(root)
    print(f"The height of the tree is: {tree_height}")

The program defines a TreeNode class to represent the nodes of the tree and a global function height to compute the height of the tree. The function height uses recursion to traverse to the furthest leaf node in each subtree, returning the maximum depth encountered. This method is efficient and concise, directly reflecting the definition of the height of a binary tree.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)