Problem
Given the root
of a binary tree, return the length of the longest path, where each node in the path has the same value. This path may or may not pass through the root.
The length of the path between two nodes is represented by the number of edges between them.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
To solve this problem:
- We are tasked with finding the length of the longest path in a binary tree where each node in the path has the same value.
- This essentially means that we need to compute the longest univalue path (a path where all nodes have the same value) in the binary tree.
Now, the longest path:
- could either pass through the root node or be entirely contained in one of the subtrees.
So,
- At each node, we calculate two components:
- The univalue path that passes through the left child.
- The univalue path that passes through the right child.
- We keep track of the longest path encountered globally.
Method 1 - DFS
Here is the recursive DFS approach:
- For each node, calculate the longest univalue path in its left and right subtree.
- If the current node’s value matches its left child, extend the left univalue path. Similarly, do the same for the right child.
- Update the global maximum path (
ans
) at each node. - The length of the path is calculated as the number of edges, so we return
max(left_length, right_length)
for each subtree.
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
. Each node of the tree is visited once, making the time complexityO(n)
(linear), wheren
is the number of nodes. - 🧺 Space complexity:
O(h)
. The space complexity depends on the depth of the recursion stack. In the worst case (skewed binary tree), it will beO(h)
, whereh
is the height of the tree.