Given a binary tree, find the length of the longest path where each node in the path has the same value. This path may or may not pass through the root. The length of path between two nodes is represented by the number of edges between them.
Input : 2 / 7 2 / 1 1 2 Output : 2 Input : 4 / 4 4 / 4 9 5 Output : 3
The idea is to recursively traverse given binary tree. We can think of any path (of nodes with the same values) in up to two directions(left and right) from it’s root. Then, for each node, we want to know what is the longest possible length extending in the left and the longest possible length extending in the right directions. The longest length that extends from the node will be 1 + length(node->left) if node->left exists, and has the same value as node. Similarly for the node->right case.
While we are computing lengths, each candidate answer will be the sum of the lengths in both directions from that node. We keep updating these answers and return the maximum one.
# Python3 program to find the length of longest
# path with same values in a binary tree.
# Helper function that allocates a
# new node with the given data and
# None left and right pointers.
def __init__(self, data):
self.val = data
self.left = self.right = None
# Function to prthe longest path
# of same values
def length(node, ans):
if (not node):
# Recursive calls to check for subtrees
left = length(node.left, ans)
right = length(node.right, ans)
# Variables to store maximum lengths
# in two directions
Leftmax = 0
Rightmax = 0
# If curr node and it’s left child has same value
if (node.left and node.left.val == node.val):
Leftmax += left + 1
# If curr node and it’s right child has same value
if (node.right and node.right.val == node.val):
Rightmax += right + 1
ans = max(ans, Leftmax + Rightmax)
return max(Leftmax, Rightmax)
# Driver function to find length of
# longest same value path
ans = 
# Driver code
if __name__ == ‘__main__’:
# Let us construct a Binary Tree
# 4 4
# 4 9 5
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)
# This code is contributed by PranchalK
- Time complexity : O(n), where n is the number of nodes in tree as every node is processed once.
- Auxiliary Space : O(h), where h is the height of tree as recursion can go upto depth h.