Longest Path with Same Values in a Binary Tree

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.

Examples:

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.

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find the length of longest
// path with same values in a binary tree.
#include <bits/stdc++.h>
using namespace std;
  
/* A binary tree node has data, pointer to
left child and a pointer to right child */
struct Node {
  int val;
  struct Node *left, *right;
};
  
/* Function to print the longest path
   of same values */
int length(Node *node, int *ans) {
  if (!node)
    return 0;
  
  // Recursive calls to check for subtrees
  int left = length(node->left, ans);
  int right = length(node->right, ans);
  
  // Variables to store maximum lengths in two directions
  int Leftmax = 0, Rightmax = 0;
  
  // If curr node and it's left child has same value
  if (node->left && node->left->val == node->val) 
    Leftmax += left + 1;  
  
  // If curr node and it's right child has same value
  if (node->right && 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*/
int longestSameValuePath(Node *root) {
  int ans = 0;
  length(root, &ans);
  return ans;
}
  
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
Node *newNode(int data) {
  Node *temp = new Node;
  temp->val = data;
  temp->left = temp->right = NULL;
  return temp;
}
  
// Driver code
int main() {
  /* Let us construct a Binary Tree
        4
       / \
      4   4
     / \   \
    4   9   5 */
  
  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);
  cout << longestSameValuePath(root);
  return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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. 
class newNode:
  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):
    return 0
     
  # 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[0] = max(ans[0], Leftmax + Rightmax) 
  return max(Leftmax, Rightmax)
     
# Driver function to find length of 
# longest same value path
def longestSameValuePath(root):
  ans = [0]
  length(root, ans) 
  return ans[0]
     
# Driver code 
if __name__ == '__main__':
      
  # Let us construct a Binary Tree 
  #      4 
  #     / \ 
  #    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
  print(longestSameValuePath(root))
    
# This code is contributed by PranchalK

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the length of longest
// path with same values in a binary tree.
using System;
  
class GFG
{
static int ans;
  
/* A binary tree node has data, pointer to
left child and a pointer to right child */
public class Node 
{
    public int val;
    public Node left, right;
};
  
/* Function to print the longest path
of same values */
static int length(Node node) 
{
    if (node == null)
        return 0;
      
    // Recursive calls to check for subtrees
    int left = length(node.left);
    int right = length(node.right);
      
    // Variables to store maximum lengths
    // in two directions
    int Leftmax = 0, Rightmax = 0;
      
    // If curr node and it's left child
    // has same value
    if (node.left != null &&
        node.left.val == node.val) 
        Leftmax += left + 1; 
      
    // If curr node and it's right child
    // has same value
    if (node.right != null && 
        node.right.val == node.val) 
        Rightmax += right + 1;
          
    ans = Math.Max(ans, Leftmax + Rightmax);
    return Math.Max(Leftmax, Rightmax);
}
  
// Function to find length of
// longest same value path
static int longestSameValuePath(Node root) 
{
    ans = 0;
    length(root);
    return ans;
}
  
/* Helper function that allocates a
new node with the given data and
null left and right pointers. */
static Node newNode(int data) 
{
    Node temp = new Node();
    temp.val = data;
    temp.left = temp.right = null;
    return temp;
}
  
// Driver code
public static void Main(String[] args) 
{
      
    /* Let us cona Binary Tree
            4
        / \
        4 4
        / \ \
        4 9 5 */
    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);
    Console.Write(longestSameValuePath(root));
}
  
// This code is contributed by 29AjayKumar

chevron_right



Output:

3

Complexity Analysis:

  • 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.


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.





Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.