687. Longest Univalue Path
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.
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.
- We need a
lengthHelperto 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.
private int result = Integer.MIN_VALUE;
- 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 initialize
Integer.MIN_VALUE. However, in this case, we want the final result subtracted by one, so we can initialize it with
root == nullreturns
size == 1return
recursive callmust be put in advance, since we need to go depth to update the global max property.
private int result;