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.