DSA Series Chapter 24 – DIAMETER OF BINARY TREE (Python Version Optimized – Single Traversal)


[JOIN OUR BLOG] for daily coding insights

DSA Series Chapter 24  – DIAMETER OF BINARY TREE (Python Version Optimized – Single Traversal)


1. Objective

To compute the diameter of a binary tree using an optimized O(n) recursive approach implemented in Python.


2. Definition (Exam-Ready)

The diameter of a binary tree is the number of nodes on the longest path between any two leaf nodes in the tree.

📌 The path may or may not pass through the root.


3. Example Binary Tree

            1
          /   \
         2     3
        / \
       4   5

Longest Path

4 → 2 → 1 → 3

Diameter

  • Nodes in longest path = 4

  • Diameter = 4


4. Why Optimized Approach?

Basic Approach Problem

  • Height is recomputed multiple times

  • Time complexity = O(n²)

Optimized Idea

  • Compute height and diameter together

  • Visit each node only once


5. Core Optimized Logic

At every node:

current_diameter = left_height + right_height + 1
update maximum diameter
return max(left_height, right_height) + 1

6. Binary Tree Node Class

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

7. Optimized Function to Compute Diameter

def diameter_of_tree(root):
    diameter = [0]  # Using list to simulate pass-by-reference

    def height(node):
        if node is None:
            return 0

        lh = height(node.left)
        rh = height(node.right)

        current_diameter = lh + rh + 1

        if current_diameter > diameter[0]:
            diameter[0] = current_diameter

        return max(lh, rh) + 1

    height(root)
    return diameter[0]

8. Line-by-Line Explanation

diameter = [0]
  • List is used to allow updates inside nested function


def height(node):
  • Computes height while updating diameter


current_diameter = lh + rh + 1
  • Longest path passing through current node


diameter[0] = current_diameter
  • Updates global maximum diameter


return max(lh, rh) + 1
  • Returns subtree height


9. Complete Python Program

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


def diameter_of_tree(root):
    diameter = [0]

    def height(node):
        if node is None:
            return 0

        lh = height(node.left)
        rh = height(node.right)

        current_diameter = lh + rh + 1

        if current_diameter > diameter[0]:
            diameter[0] = current_diameter

        return max(lh, rh) + 1

    height(root)
    return diameter[0]


# Driver Code
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)

print("Diameter of the binary tree:", diameter_of_tree(root))

10. Output

Diameter of the binary tree: 4

11. Time and Space Complexity

Time Complexity

  • O(n)
    Each node is visited exactly once.

Space Complexity

  • O(h) due to recursion stack


12. Important Exam Points

  • Diameter can be measured in nodes or edges

  • Always clarify question requirement

  • Optimized approach preferred in interviews

  • Path may bypass root


13. Common Beginner Mistakes

  • Confusing diameter with height

  • Forgetting +1 for current node

  • Using global variables unnecessarily

  • Returning diameter instead of height


14. Comparison: C vs Python Approach

AspectCPython
ReferencePointerList
TraversalSingleSingle
ComplexityO(n)O(n)

15. Learning Outcome

After this post, learners can:

  • Implement optimized diameter algorithm

  • Analyze tree properties efficiently

  • Solve interview-level problems

  • Write clean recursive Python code

ALSO CHECK 

DS(Data Structure) Python&C Edition

DSA Series Chapter 1 Time & Space Complexity ( C Edition)

DSA Series Chapter 2 Arrays  (C Version)


DSA Series Chapter 2 Arrays  (Python Version)

DSA Series Chapter 3 Strings (C Version)


DSA Series Chapter 3 Strings (Python Version)


DSA Series Chapter 4 Linked Lists (Python Version)


DSA Series Chapter 4 Linked Lists (C Version)


DSA Series Chapter 5 Stacks (Python Version)


DSA Series Chapter 5  Stacks  (C Version)




















DSA Series Chapter 13 - Binary Tree traversal, BFS, DFT/DFS, Preorder Traversal In Binary Tree


DSA Series Chapter 14 - InOrder Traversal (Binary Tree C Version)


DSA Series Chapter 14 - InOrder Traversal (Binary Tree Python Version)

 

DSA Series Chapter 15 – POSTORDER TRAVERSAL (BINARY TREE)(Python Version)


DSA Series Chapter 15 – POSTORDER TRAVERSAL (BINARY TREE)(C Version)


DSA Series Chapter 16 – LEVEL ORDER TRAVERSAL(BINARY TREE BFS)(C Version)


DSA Series Chapter 16 – LEVEL ORDER TRAVERSAL(BINARY TREE BFS)(Python Version)



DSA Series Chapter 19 : DELETION IN BINARY TREE(C Version)

DSA Series Chapter 19 : DELETION IN BINARY TREE(Python Version)


DSA Series Chapter 20 – HEIGHT OF BINARY TREE(C Version)

DSA Series Chapter 20 – HEIGHT OF BINARY TREE(Python Version)






Tail Recursion Optimization: How Compilers Convert Recursion Into Iteration


Advanced Recursion: Memoization vs. Tabulation — The Deep Optimization Blueprint for Professionals


Advanced Sorting Algorithms: Merge Sort Internals — Merge Tree, Cache Behavior & Real Cost Analysis


Enjoyed this post? [Follow here] for daily coding insights

Comments