Diameter of Binary Tree in Python

The diameter of a binary tree is the length of the longest path between any two nodes in the tree. This path may or may not pass through the root node. We can solve this problem using depth-first search (DFS) to calculate the height of each subtree and track the maximum diameter found.

1 2 3 4 5 Diameter = 3 (path: 4?2?1?3 or 5?2?1?3)

Algorithm Explanation

The algorithm uses DFS to calculate the height of each subtree. For each node, the diameter passing through that node is the sum of heights of its left and right subtrees. We track the maximum diameter found during traversal.

Implementation

class TreeNode:
    def __init__(self, data, left=None, right=None):
        self.data = data
        self.left = left
        self.right = right

def insert(temp, data):
    que = []
    que.append(temp)
    while len(que):
        temp = que[0]
        que.pop(0)
        if not temp.left:
            temp.left = TreeNode(data)
            break
        else:
            que.append(temp.left)
        if not temp.right:
            temp.right = TreeNode(data)
            break
        else:
            que.append(temp.right)

def make_tree(elements):
    tree = TreeNode(elements[0])
    for element in elements[1:]:
        insert(tree, element)
    return tree

class Solution:
    def diameterOfBinaryTree(self, root):
        self.ans = 0
        self.dfs(root)
        return self.ans
    
    def dfs(self, node):
        if not node:
            return 0
        left = self.dfs(node.left)
        right = self.dfs(node.right)
        self.ans = max(self.ans, left + right)
        return max(left + 1, right + 1)

# Example usage
root = make_tree([1, 2, 3, 4, 5])
solution = Solution()
print(solution.diameterOfBinaryTree(root))
3

How It Works

The DFS function returns the height of each subtree while tracking the maximum diameter:

  • Base case: If node is None, return height 0
  • Recursive calls: Get heights of left and right subtrees
  • Update diameter: Current diameter through this node is left + right
  • Return height: Height of current subtree is max(left, right) + 1

Time and Space Complexity

Complexity Value Reason
Time O(n) Visit each node once
Space O(h) Recursion stack depth equals tree height

Conclusion

The diameter of a binary tree can be efficiently calculated using DFS in O(n) time. The key insight is that for each node, we calculate both the height of its subtree and update the global maximum diameter.

Updated on: 2026-03-25T07:19:02+05:30

659 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements