human
Longest Path with Same Values in a Binary Tree | 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 .
Driver function to find length of longest same value path.
Helper function that allocates a new node with the given data and None left and right pointers ..
Driver code.
Let us construct a Binary Tree 4 / \ 4 4 / \ \ 4 9 5"
How can the above be solved in Python?
assistant
#Here is code to longest Path with Same Values in a Binary Tree and the other steps required.
 def length ( node , ans ) :
	if ( not node ) :
		return 0
	left = length ( node . left , ans )
	right = length ( node . right , ans )
	Leftmax = 0
	Rightmax = 0
	if ( node . left and node . left . val == node . val ) :
		Leftmax += left + 1
	if ( node . right and node . right . val == node . val ) :
		Rightmax += right + 1
	ans [ 0 ] = max ( ans [ 0 ] , Leftmax + Rightmax )
	return max ( Leftmax , Rightmax )
def longestSameValuePath ( root ) :
	ans = [ 0 ]
	length ( root , ans )
	return ans [ 0 ]
class newNode :
	def __init__ ( self , data ) :
		self . val = data
		self . left = self . right = None
if __name__ == ' _ _ main _ _ ' :
	root = None
	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 )
	print ( longestSameValuePath ( root ) )