{x}
blog image

Diameter of Binary Tree

Given the root of a binary tree, return the length of the diameter of the tree.

The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

The length of a path between two nodes is represented by the number of edges between them.

 

Example 1:

Input: root = [1,2,3,4,5]
Output: 3
Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].

Example 2:

Input: root = [1,2]
Output: 1

 

Constraints:

  • The number of nodes in the tree is in the range [1, 104].
  • -100 <= Node.val <= 100

Solution Explanation: Diameter of Binary Tree

The problem asks for the diameter of a binary tree, which is the length of the longest path between any two nodes in the tree. This path doesn't necessarily pass through the root. The length of a path is the number of edges it contains.

Approach: Depth-First Search (DFS)

The most efficient way to solve this problem is using Depth-First Search (DFS). We can achieve this in a single pass of the tree. The key idea is to realize that the diameter can be calculated by considering each node as a potential midpoint of the longest path. For each node, the diameter passing through that node is the sum of the depths of its left and right subtrees.

The algorithm works as follows:

  1. Base Case: If the current node is null, return 0 (depth is 0).

  2. Recursive Calls: Recursively calculate the depth of the left subtree (leftDepth) and the right subtree (rightDepth) using DFS.

  3. Update Maximum Diameter: Update the global maximum diameter (ans) with the maximum of the current ans and the sum of leftDepth and rightDepth.

  4. Return Depth: Return the maximum of leftDepth and rightDepth plus 1 (to account for the current node). This represents the depth of the subtree rooted at the current node.

Time and Space Complexity Analysis

  • Time Complexity: O(N), where N is the number of nodes in the binary tree. Each node is visited exactly once during the DFS traversal.

  • Space Complexity: O(H), where H is the height of the binary tree. This is due to the recursive call stack space used during DFS. In the worst case (a skewed tree), H can be equal to N, resulting in O(N) space complexity. In the best case (a balanced tree), H = log₂(N), resulting in O(log₂(N)) space complexity.

Code Implementation (Python)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def diameterOfBinaryTree(self, root: TreeNode) -> int:
        self.diameter = 0  # Initialize the diameter
 
        def dfs(node):
            if not node:
                return 0  # Base case: empty subtree has depth 0
 
            left_depth = dfs(node.left)
            right_depth = dfs(node.right)
 
            # Update diameter if necessary
            self.diameter = max(self.diameter, left_depth + right_depth)
 
            return max(left_depth, right_depth) + 1  # Return the depth of the subtree
 
        dfs(root)
        return self.diameter

The code in other languages follows the same logic with minor syntax differences. Refer to the provided code snippets for the implementations in Java, C++, Go, TypeScript, Rust, JavaScript, and C#. All implementations maintain the same O(N) time and O(H) space complexity.