Hide sidebar

Diameter of Binary Tree

Diameter of Binary Tree

TreesDFS
EasyLeetCode #543
20 min

Problem Statement

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.

Example

Example 1:

Input: root = [1,2,3,4,5]

45231

Output: 3

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

Solution (Depth-First Search)

The diameter of a tree is the number of edges on the longest path between any two nodes. This path might not pass through the root.

We can solve this with a single DFS traversal. For each node, we can calculate the "depth" of its left and right subtrees. The longest path *through that node* is the sum of its left and right depths. We can keep a global maximum of these path lengths as we traverse the tree.

Algorithm Steps

  • Initialize a variable diameter to 0, which will be updated during the traversal.
  • Create a recursive helper function, `dfs(node)`, that returns the height of the subtree rooted at `node`.
  • Base Case: If `node` is null, return -1 (or 0, depending on height definition; here we use -1 for edge count).
  • Recursively call `dfs` on the left and right children to get their heights.
  • The diameter at the current node is `left_height + right_height + 2` (adding 2 for the edges to the children). Update the global `diameter` if this is larger.
  • The function should return the height of the current node's subtree: `1 + max(left_height, right_height)`.
  • The final `diameter` value is the answer.
12453
Max Diameter Found: 0
DFS on node 1. Recursing on left child.
Diameter of Binary Tree Solution

# 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: Optional[TreeNode]) -> int:
        self.diameter = 0
        
        def dfs(node):
            if not node:
                return -1
            
            left_height = dfs(node.left)
            right_height = dfs(node.right)
            
            # The diameter at this node is the sum of heights of left and right subtrees
            self.diameter = max(self.diameter, left_height + right_height + 2)
            
            # Return the height of the subtree rooted at this node
            return 1 + max(left_height, right_height)

        dfs(root)
        return self.diameter