Description:

The diameter of binary tree is a longest path or route between any two any nodes in a tree. The path may or may not pass through the route.The diameter of tree also called its width is the number of nodes on the longest path between two end nodes.

Example:

Diameter 9 nodes through root Diameter 9 nodes not through root

Program:

class BTNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def height(node):
if node is None:
return 0 ;
return 1 + max(height(node.left) ,height(node.right))
def diameter(root):
if root is None:
return 0;
left_height = height(root.left)
right_height = height(root.right)
left_diameter = diameter(root.left)
right_diameter = diameter(root.right)
return max(left_height + right_height + 1, max(left_diameter, right_diameter))
root = BTNode(1)
root.left = BTNode(2)
root.right = BTNode(3)
root.left.left = BTNode(4)
root.left.right = BTNode(5)
print("Diameter of given binary tree is :",(diameter(root)))

Output:

Diameter of given binary tree is : 4

>>>

## Comments