• Skip to main content
  • Skip to secondary menu
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Contact Us

All about code

  • Java
    • Spring
      • Spring Boot
      • Spring Cloud
    • Java Miscellaneous Tips
    • Java Design Patterns
  • Data Structures and Algorithms
    • Algorithms
    • Data Structures
  • Thoughts and Stories
  • AI

Binary Tree’s Diameter: Easy Explanation to Find its value

laptop infographic online business 6087062

Introduction

The longest path length between any two nodes of a binary tree is called its diameter (Binary Tree’s Diameter). This path may or may not cross the root. Importantly, the length is measured by the number of edges between the nodes on this path, not the number of nodes.

To solve this problem efficiently, a recursive approach is often used, where we simultaneously compute the height of each subtree and keep track of the longest path encountered so far.

Approach to the Problem of the Binary Tree’s Diameter

To calculate the diameter, we need to determine the longest path between two nodes. For any given node, the longest path that passes through it is the sum of the heights of its left and right subtrees. As we calculate the height recursively, we can update the maximum diameter whenever a longer path is found.

This involves:

  • A recursive function to calculate the height of a node
  • Keeping a reference to the maximum diameter found so far
  • Updating this maximum during each recursive call based on the left and right subtree heights

Java Implementation

Here’s an implementation in Java to find the diameter of a binary tree:

public class BinaryTreeDiameter {
    private int diameter = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        computeHeight(root);
        return diameter;
    }

    private int computeHeight(TreeNode node) {
        if (node == null) return 0;

        int leftHeight = computeHeight(node.leftNode);
        int rightHeight = computeHeight(node.rightNode);

        diameter = Math.max(diameter, leftHeight + rightHeight);

        return Math.max(leftHeight, rightHeight) + 1;
    }

    public static void main(String[] args) {
        /*
            Example Tree:
                  1
                 / \
                2   3
               / \     
              4   5    

            Expected diameter: 3 (path: 4 -> 2 -> 1 -> 3)
        */
    	BinaryTreeDiameter binaryTreeDiameter = new BinaryTreeDiameter();
        TreeNode root = binaryTreeDiameter.new TreeNode(1);
        root.leftNode = binaryTreeDiameter.new TreeNode(2);
        root.rightNode = binaryTreeDiameter.new TreeNode(3);
        root.leftNode.leftNode = binaryTreeDiameter.new TreeNode(4);
        root.leftNode.rightNode = binaryTreeDiameter.new TreeNode(5);

        BinaryTreeDiameter tree = new BinaryTreeDiameter();
        int result = tree.diameterOfBinaryTree(root);
        System.out.println("Diameter of the tree is: " + result);
    }
    
    class TreeNode {
        int nodeVal;
        TreeNode leftNode;
        TreeNode rightNode;

        TreeNode(int nodeVal) {
            this.nodeVal = nodeVal;
        }
    }
}

Time and Space Complexity for Binary Tree’s Diameter

Time Complexity: O(n), where n is the number of nodes in the tree. Each node is visited once.
Space Complexity: O(h), where h is the height of the tree, due to recursive call stack.

Conclusion

This approach offers a concise and efficient way to compute the diameter of a binary tree. By calculating the height and updating the diameter in the same traversal, we avoid redundant computations and achieve optimal performance.

You can find the example code on Github.

Primary Sidebar

Social

  • Facebook
  • LinkedIn
  • Twitter

Archives

  • May 2026
  • April 2026
  • March 2026
  • August 2025
  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • December 2024
  • October 2024
  • August 2024
  • July 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • September 2023
  • May 2023
  • March 2023
  • January 2023
  • November 2022
  • September 2022
  • August 2022

Recent Posts

  • Better Avoid Spring Boot Lazy-initialization @PostConstruct Trap
  • How To Handle Large Datasets in Spring Boot
  • How to Log HTTP Incoming Requests in Spring Boot
  • How to Reliably Implement Post-Commit Actions in Spring
  • Brief and Easy Explanation of HATEOAS

TAGS

Algorithms Apache POI Backtracking Date Structures Dynamic Programming engineering Graphs Greedy Horror Stories HSSF Java Java New Features Java Principles Java tips real life Sorting Spring Boot Spring Cloud Strings Trees

Footer

Privacy Policy Cookie Policy Terms and Conditions