Reference: LeetCode
Difficulty: Easy
Problem
Given a binary tree, find 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 path between two nodes is represented by the number of edges between them.
Note: The given binary tree has not more than 10000 nodes. The height of the tree is not more than 1000.
Example:
1 | Input: |
1 | Input: |
Analysis
Note that the following 0-1-2-3
is not a path (degree should be less than or equal to 2). In other words, a path can only be a list.
1 | 0 |
Methods:
- Recursion
- We need a
lengthHelper
to return the max value on one side. Plus the root’s size $1$ only if a child has the same value as the root does, or $2$ if both children satisfy this constraint. - Time: $O(N)$
- Space: $O(h)$
- We need a
Check out the improved code below directly. Bad code is just a record of my first attempt.
Bad Code:
1 | private int result = Integer.MIN_VALUE; |
Improved code:
- I first compute the length as the number of nodes in the path and I will subtract one at the end.
- Since this problem is a
counting problem
, we can initializeresult
as0
instead ofInteger.MIN_VALUE
. However, in this case, we want the final result subtracted by one, so we can initialize it with1
.root == null
returns0
.size == 1
return0
.
recursive call
must be put in advance, since we need to go depth to update the global max property.
1 | private int result; |