Diameter of Binary Tree
Diameter of Binary Tree
TreesDFS
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]
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.
Max Diameter Found: 0
DFS on node 1. Recursing on left child.
Diameter of Binary Tree Solution