Longest Univalue Path


@cheesewraps A path is between two nodes, so both trees have an expected answer of 2.

@cheesewraps
Count number of edges and not number of nodes. 2 is correct answer here.

Same idea.
class Solution { int max = 0; public int longestUnivaluePath(TreeNode root) { max = 0; if(root == null) return 0; return Math.max(longestUnivaluePathHelper(root.left,root.val) + longestUnivaluePathHelper(root.right,root.val),max); } public int longestUnivaluePathHelper(TreeNode root,int parent_val){ if(root == null) return 0; int left = longestUnivaluePathHelper(root.left,root.val); int right = longestUnivaluePathHelper(root.right,root.val); max = Math.max(max,left + right); return root.val == parent_val ? 1 + Math.max(left,right) : 0; } }

@awice
Could you explain why is answer 2 here ? There is only one path between 44( left) and 44(right)...max of both is 1
1
/
4 5
/ \
4 4 5

@12GitTho10
Question is asking for longest path which has same node value
combine both left and right
so the path is
leftmost 4 > middle 4 > right down 4as all node values is 4 we have to consider all
Hope this will help.
