Close Menu
    Code and Debug
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook X (Twitter) Instagram YouTube WhatsApp
    • Home
    • Our Courses
    • Blog
    • About Us
    • Contact Us
    Facebook Instagram YouTube LinkedIn WhatsApp
    Code and Debug – BlogCode and Debug – Blog
    Code and Debug – BlogCode and Debug – Blog
    Home»Data Structures & Algorithms»Diameter of Binary Tree
    Data Structures & Algorithms

    Diameter of Binary Tree

    Anirudh KhuranaBy Anirudh Khurana14 May 2025Updated:16 November 2026No Comments5 Mins Read
    Share Facebook Twitter Pinterest LinkedIn Tumblr Reddit Telegram Email
    Diagram of a binary tree with the longest path (diameter) between two leaf nodes highlighted
    Share
    Facebook Twitter LinkedIn Pinterest Email

    Learn how to calculate the diameter (longest path) of a binary tree in one pass using recursion. Clear, step-by-step code and explanations perfect for LeetCode practice. You can solve the problem by visiting this Problem Link.

    Content:
     [show]
    • What the Problem Asks
    • How We’ll Solve It
    • Code Implementation
    • Step-By-Step Explanation
    • Dry Run on Example
    • Time & Space Complexity

    What the Problem Asks

    LeetCode 543: Diameter of Binary Tree
    Given a binary tree, find the length of the diameter of the tree.
    The diameter is the number of edges on the longest path between any two nodes in the tree.

    Key point: The longest path might go through the root or any other node.

    Example Tree:

         1
        / \
       2   3
      / \
     4   5

    The longest path is 4 → 2 → 1 → 3, which has 3 edges. So the diameter is 3.

    Interactive Visualizer: Heights Bottom-Up

    Pick an example or type a tree in level order (use null for missing children), then press Next. Each node shows its height once it is computed, and the final step highlights one longest path.


    How We’ll Solve It

    1. Calculate Height and Track Diameter at Once
      • For each node, find the height of its left subtree and right subtree.
      • A path that passes through this node has length leftHeight + rightHeight (in edges).
      • Keep a global diameter variable and update it whenever leftHeight + rightHeight is bigger.
    2. Recursive Height Function
      • Returns the height of the subtree (in nodes).
      • While returning, it also updates the diameter.

    This way, we only walk the tree once (O(N) time), and we don’t need extra data structures.

    Code Implementation

    class Solution:
        diameter = 0  # holds the maximum diameter found
    
        def calculateHeight(self, root):
            # Base case: empty tree has height 0
            if not root:
                return 0
    
            # Recursively find heights of left and right subtrees
            leftHeight = self.calculateHeight(root.left)
            rightHeight = self.calculateHeight(root.right)
    
            # Update diameter: path through root uses leftHeight + rightHeight edges
            self.diameter = max(self.diameter, leftHeight + rightHeight)
    
            # Return the height of this subtree (in nodes)
            return 1 + max(leftHeight, rightHeight)
    
        def diameterOfBinaryTree(self, root: Optional[TreeNode]) -> int:
            # Initialize diameter and start recursion
            self.diameter = 0
            self.calculateHeight(root)
            return self.diameter
    class Solution {
        private int diameter = 0; // holds the maximum diameter found
    
        private int calculateHeight(TreeNode root) {
            // Base case: empty tree has height 0
            if (root == null) return 0;
    
            // Recursively find heights of left and right subtrees
            int leftHeight = calculateHeight(root.left);
            int rightHeight = calculateHeight(root.right);
    
            // Update diameter: path through root uses leftHeight + rightHeight edges
            diameter = Math.max(diameter, leftHeight + rightHeight);
    
            // Return the height of this subtree (in nodes)
            return 1 + Math.max(leftHeight, rightHeight);
        }
    
        public int diameterOfBinaryTree(TreeNode root) {
            // Initialize diameter and start recursion
            diameter = 0;
            calculateHeight(root);
            return diameter;
        }
    }
    class Solution {
        int diameter = 0; // holds the maximum diameter found
    
        int calculateHeight(TreeNode* root) {
            // Base case: empty tree has height 0
            if (!root) return 0;
    
            // Recursively find heights of left and right subtrees
            int leftHeight = calculateHeight(root->left);
            int rightHeight = calculateHeight(root->right);
    
            // Update diameter: path through root uses leftHeight + rightHeight edges
            diameter = max(diameter, leftHeight + rightHeight);
    
            // Return the height of this subtree (in nodes)
            return 1 + max(leftHeight, rightHeight);
        }
    
    public:
        int diameterOfBinaryTree(TreeNode* root) {
            // Initialize diameter and start recursion
            diameter = 0;
            calculateHeight(root);
            return diameter;
        }
    };

    Step-By-Step Explanation

    1. Global Variable diameter
      • We store the largest sum of left and right subtree heights (in edges).
    2. calculateHeight(root)
      • If root is None, height is 0.
      • Otherwise:
        • Compute leftHeight = calculateHeight(root.left).
        • Compute rightHeight = calculateHeight(root.right).
        • Update diameter with leftHeight + rightHeight if it’s larger.
        • Return 1 + max(leftHeight, rightHeight) as the subtree height.
    3. diameterOfBinaryTree(root)
      • Reset diameter to 0.
      • Call calculateHeight(root).
      • Return the final diameter.

    This works because every node gets a chance to consider the path that goes through it. The longest such path anywhere in the tree is our answer.


    Dry Run on Example

           1
          / \
         2   3
        / \
       4   5
    1. calculateHeight(4) → left and right are None → heights 0,0 → diameter = max(0,0) → returns 1
    2. calculateHeight(5) → same → returns 1
    3. At node 2:
      • leftHeight=1, rightHeight=1 → diameter = max(0,1+1)=2
      • returns 1 + max(1,1)=2
    4. calculateHeight(3) → returns 1
    5. At node 1:
      • leftHeight=2, rightHeight=1 → diameter = max(2,2+1)=3
      • returns 1 + max(2,1)=3

    Final diameter = 3.


    Time & Space Complexity

    • Time: O(N) — we visit each node once.
    • Space: O(H) — recursion stack up to tree height H (worst-case O(N) for skewed tree, O(log N) for balanced tree).

    Frequently Asked Questions

    What is the diameter of a binary tree?

    It is the number of edges on the longest path between any two nodes in the tree. For the tree [1,2,3,4,5] the diameter is 3, for example the path 4 → 2 → 1 → 3.

    Does the diameter always pass through the root?

    No. The longest path can sit entirely inside one subtree, which is why the solution checks leftHeight + rightHeight at every node, not only at the root. Try the “Not through root” example in the visualizer.

    What is the time and space complexity of the diameter solution?

    Each node is visited once, so it runs in O(n) time. The recursion uses O(h) space, where h is the height of the tree: O(log n) for a balanced tree and O(n) for a skewed one.

    Why is the naive solution O(n²)?

    Computing the height separately for every node visits the same subtrees again and again. The one-pass solution returns the height and updates the diameter in the same call, so each node is processed only once.

    What is the difference between height and diameter?

    Height is the longest path from a node down to a leaf. Diameter is the longest path between any two nodes, which at its highest point equals the left height plus the right height of some node.


    Join our free DSA COURSE

    For any changes to the article, kindly email at co**@**********ug.in or contact us at +91-9712928220.

    Binary Trees
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleMaximum Depth of Binary Tree | Explained with Examples
    Next Article BFS Traversal in Graph | Explained using Code
    Anirudh Khurana
    • Website

    Anirudh Khurana is the founder of Code and Debug, an Indian EdTech platform that helps students and working professionals crack coding interviews and move into data and AI roles. He teaches DSA, Python, SQL, data engineering and machine learning through live bootcamps and his YouTube channel, Code and Debug, which has over 50,000 subscribers. Every guide on this blog is written or reviewed by him and tested with real code.

    Related Posts

    Python

    100 Python Programs with Examples and Output (Run Online + PDF)

    1 December 2026
    SQL

    SQL Queries with Examples: Run Online, 50 Practice Questions and Free PDF

    27 November 2026
    Data Structures & Algorithms

    DSA Interview Cheat Sheet: All Patterns You Need to Know

    4 April 2026
    Add A Comment
    Leave A Reply Cancel Reply

    Categories
    • AI & Machine Learning (8)
    • Data Structures & Algorithms (243)
      • Beginner (84)
      • Expert (52)
      • Intermediate (106)
    • Interview Questions (9)
    • Pandas (1)
    • Python (2)
    • Resume (1)
    • SQL (3)
    Recent Posts

    100 React Interview Questions and Answers (2026) + Free PDF

    3 December 2026

    100 JavaScript Interview Questions and Answers (2026) + Free PDF

    2 December 2026

    100 Python Programs with Examples and Output (Run Online + PDF)

    1 December 2026

    100 Java Interview Questions and Answers (Freshers to Experienced)

    30 November 2026

    SQL Queries with Examples: Run Online, 50 Practice Questions and Free PDF

    27 November 2026
    Facebook Instagram YouTube LinkedIn WhatsApp
    © 2025 Code and Debug. All rights reserved.

    Type above and press Enter to search. Press Esc to cancel.