solution: DFS O(N), O(N)
class Solution {
int res = 0;
public int longestUnivaluePath(TreeNode root) {
if (root == null) {
return 0;
}
dfs(root, root.val);
return res;
}
// Returns the length of the longest path under the root that have the value same as the root.
// The path could either be on the left or right child of the root.
public int dfs(TreeNode node, int val) {
if (node == null) {
return 0;
}
int left = dfs(node.left, node.val);
int right = dfs(node.right, node.val);
// the result should be left + right
res = Math.max(res, left + right);
if (node.val == val) {
// only keep one side for higher level node
return 1 + Math.max(left, right);
}
return 0;
}
// left + right is the length of a path that goes from left subtree and through the current root to its right subtree.
// And from current root, we only return the longer branch between left and right.
}