Similar questions:
Time = O(n), space = O(h)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
int max = 0;
public int longestUnivaluePath(TreeNode root) {
helper(root);
return max;
}
private int helper(TreeNode root) {
if (root == null) {
return 0;
}
int left = helper(root.left);
int right = helper(root.right);
left = (root.left != null && root.left.val == root.val) ? left + 1 : 0;
right = (root.right != null && root.right.val == root.val) ? right + 1 : 0;
max = Math.max(max, left + right);
return Math.max(left, right);
}
}