Longest Path with Same Values in a Binary Tree | Java program to find the length of longest path with same values in a binary tree . ; A binary tree node has data , pointer to left child and a pointer to right child ; Function to print the longest path of same values ; Recursive calls to check for subtrees ; Variables to store maximum lengths in two directions ; If curr node and it 's left child  has same value ; If curr node and it 's right child  has same value ; Function to find length of longest same value path ; Helper function that allocates a new node with the given data and null left and right pointers . ; Driver code ; Let us cona Binary Tree 4 / \ 4 4 / \ \ 4 9 5
class GFG { static int ans ; static class Node { int val ; Node left , right ; } ; static int length ( Node node ) { if ( node == null ) return 0 ; int left = length ( node . left ) ; int right = length ( node . right ) ; int Leftmax = 0 , Rightmax = 0 ; if ( node . left != null && node . left . val == node . val ) Leftmax += left + 1 ; if ( node . right != null && node . right . val == node . val ) Rightmax += right + 1 ; ans = Math . max ( ans , Leftmax + Rightmax ) ; return Math . max ( Leftmax , Rightmax ) ; } static int longestSameValuePath ( Node root ) { ans = 0 ; length ( root ) ; return ans ; } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . val = data ; temp . left = temp . right = null ; return temp ; } public static void main ( String [ ] args ) { Node root = null ; root = newNode ( 4 ) ; root . left = newNode ( 4 ) ; root . right = newNode ( 4 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 9 ) ; root . right . right = newNode ( 5 ) ; System . out . print ( longestSameValuePath ( root ) ) ; } }