Given a Binary Tree consisting of N nodes, the task is to find the length of the longest path from any node to the bottom of the tree such that all the node values form an Arithmetic Progression.
Examples:
Input:
Output: 4
Explanation:
From the above given tree, the longest path with node values forming an AP is {6, 9, 12, 15} (Length = 4).Input:
Output: 2
Approach: The given problem can be solved by using recursion and performing the DFS Traversal on the given tree. The idea is to keep track of the difference between the current root node and the next descendant node and update the length of the longest path accordingly. Follow the steps below to solve the given problem:
- Initialize a variable, say maxLength as 1 that stores the maximum length of the path from any node to the bottom of the tree forming an Arithmetic Progression.
- Define a function, say dfs(root, currentDifference, count, maxLength) that takes the current root node, current difference, count of nodes forming AP, and the resultant maximum length as the parameter and perform the following steps:
- If the root’s left node exists, then perform the following steps:
- Find the difference between the value of the root and its left node.
- If the difference is found to be currentDifference, then update the value of maxLength to the maximum of maxLength and (count + 1) and recursively call for the function dfs(root->left, currentDifference, count + 1, maxLength).
- Otherwise, recursively call for the dfs(root->left, difference, 2, maxLength).
- If the root’s right node exists, then perform the following steps:
- Find the difference between the value of the root and its right node.
- If the difference is found to be currentDifference, then update the value of maxLength to the maximum of maxLength and (count + 1) and recursively call for the function dfs(root->right, currentDifference, count + 1, maxLength).
- Otherwise, recursively call for the dfs(root->left, difference, 2, maxLength).
- If the root’s left node exists, then perform the following steps:
- If the left child of the given root node exists, then call for the dfs(root->left, difference, 2, maxLength) where the difference is the difference between the value of the root and its left node.
- If the right child of the given root node exists, then call for the dfs(root->right, difference, 2, maxLength) where the difference is the difference between the value of the root and its right node.
- After completing the above steps, print the value of maxLength as the resultant maximum length of the path from any node to the bottom of the tree forming an Arithmetic Progression.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include "bits/stdc++.h"using namespace std;Â
// Structure of the Tree Nodestruct Tree {Â Â Â Â int val;Â Â Â Â Tree *left, *right;};Â
// Function to create a new nodeTree* newNode(int data){Â Â Â Â Tree* temp = new Tree();Â Â Â Â temp->val = data;Â Â Â Â temp->left = temp->right = NULL;Â Â Â Â return temp;}Â
// Function to perform DFS Traversal// to find the maximum length of a path// to a bottom node forming an APvoid dfs(Tree* root, int currentDifference,         int count, int& maxLength){    // If the root's left child exists    if (root->left) {Â
        // Calculate the difference        int difference = root->left->val                         - root->val;Â
        // If the difference is same        // as the current difference        if (difference == currentDifference) {            dfs(root->left, currentDifference,                count + 1, maxLength);Â
            // Update the maxLength            maxLength = max(maxLength,                            count + 1);        }Â
        // Otherwise        else {            dfs(root->left, difference,                2, maxLength);        }    }Â
    // If the root's right child exists    if (root->right) {Â
        // Find the difference        int difference = root->right->val                         - root->val;Â
        // If the difference is the same        // as the current difference        if (difference == currentDifference) {Â
            dfs(root->right, currentDifference,                count + 1, maxLength);Â
            // Update the maxLength            maxLength = max(maxLength,                            count + 1);        }Â
        // Otherwise        else {            dfs(root->right, difference,                2, maxLength);        }    }}Â
// Function to find the maximum length// of the path from any node to bottom// of the tree forming an APint maximumLengthAP(Tree* root){Â
    // Base Cases    if (root == NULL)        return 0;Â
    if (root->left == NULL        and root->right == NULL) {        return 1;    }Â
    // Stores the resultant    // maximum length of the path    int maxLength = 2;Â
    // If the root's left child exists    if (root->left) {Â
        int difference = root->left->val                         - root->val;        dfs(root->left, difference, 2,            maxLength);    }Â
    // If the root's right child exists    if (root->right) {        int difference = root->right->val                         - root->val;        dfs(root->right, difference, 2,            maxLength);    }Â
    // Return the maximum length obtained    return maxLength;}Â
// Driver Codeint main(){Â
    // Given Tree    Tree* root = newNode(6);    root->right = newNode(9);    root->right->left = newNode(7);    root->right->right = newNode(12);    root->right->right->right = newNode(15);Â
    cout << maximumLengthAP(root);Â
    return 0;} |
Java
// Java program for the above approachimport java.lang.*;import java.util.*;Â
class GFG{Â Â Â Â Â static int maxLength;Â Â Â Â Â Â Â Â // TreeNode classstatic class Node{Â Â Â Â public int val;Â Â Â Â public Node left, right;};Â
static Node newNode(int key){Â Â Â Â Node temp = new Node();Â Â Â Â temp.val = key;Â Â Â Â temp.left = temp.right = null;Â Â Â Â return temp;}Â
// Function to perform DFS Traversal// to find the maximum length of a path// to a bottom node forming an APstatic void dfs(Node root, int currentDifference,                int count){         // If the root's left child exists    if (root.left != null)     {                 // Calculate the difference        int difference = root.left.val - root.val;Â
        // If the difference is same        // as the current difference        if (difference == currentDifference)        {            dfs(root.left, currentDifference,                count + 1);Â
            // Update the maxLength            maxLength = Math.max(maxLength,                                 count + 1);        }Â
        // Otherwise        else        {            dfs(root.left, difference, 2);        }    }Â
    // If the root's right child exists    if (root.right != null)    {                 // Find the difference        int difference = root.right.val - root.val;Â
        // If the difference is the same        // as the current difference        if (difference == currentDifference)        {            dfs(root.right, currentDifference,                count + 1);Â
            // Update the maxLength            maxLength = Math.max(maxLength,                                 count + 1);        }Â
        // Otherwise        else        {            dfs(root.right, difference, 2);        }    }}Â
// Function to find the maximum length// of the path from any node to bottom// of the tree forming an APstatic int maximumLengthAP(Node root){         // Base Cases    if (root == null)        return 0;Â
    if (root.left == null &&         root.right == null)    {        return 1;    }Â
    // Stores the resultant    // maximum length of the path     maxLength = 2;Â
    // If the root's left child exists    if (root.left != null)    {        int difference = root.left.val - root.val;        dfs(root.left, difference, 2);    }Â
    // If the root's right child exists    if (root.right != null)    {        int difference = root.right.val - root.val;        dfs(root.right, difference, 2);    }Â
    // Return the maximum length obtained    return maxLength;}   Â
// Driver codepublic static void main(String[] args){ Â
    // Given Tree    Node root = newNode(6);    root.right = newNode(9);    root.right.left = newNode(7);    root.right.right = newNode(12);    root.right.right.right = newNode(15);         System.out.println(maximumLengthAP(root));}}Â
// This code is contributed by offbeat |
Python3
# Python3 program for the above approachmaxLength = 2Â
class Node:       # Constructor to set the data of    # the newly created tree node    def __init__(self, key):        self.val = key        self.left = None        self.right = NoneÂ
# Function to perform DFS Traversal# to find the maximum length of a path# to a bottom node forming an APdef dfs(root, currentDifference, count):Â Â Â Â Â Â Â Â Â global maxLengthÂ
    # If the root's left child exists    if (root.left != None):        # Calculate the difference        difference = root.left.val - root.valÂ
        # If the difference is same        # as the current difference        if (difference == currentDifference):                     dfs(root.left, currentDifference, count + 1)Â
            # Update the maxLength            maxLength = max(maxLength, count + 1)         Â
        # Otherwise        else:            dfs(root.left, difference, 2)Â
    # If the root's right child exists    if (root.right != None):        # Find the difference        difference = root.right.val - root.valÂ
        # If the difference is the same        # as the current difference        if (difference == currentDifference):                     dfs(root.right, currentDifference, count + 1)Â
            # Update the maxLength            maxLength = max(maxLength, count + 1)Â
        # Otherwise        else:            dfs(root.right, difference, 2)Â
# Function to find the maximum length# of the path from any node to bottom# of the tree forming an APdef maximumLengthAP(root):Â
    global maxLength         # Base Cases    if (root == None):        return 0Â
    if (root.left == None and root.right == None):        return 1Â
    # If the root's left child exists    if (root.left != None):        difference = root.left.val - root.val        dfs(root.left, difference, 2)Â
    # If the root's right child exists    if (root.right != None):        difference = root.right.val - root.val        dfs(root.right, difference, 2)Â
    # Return the maximum length obtained    return maxLengthÂ
# Given Treeroot = Node(6)root.right = Node(9)root.right.left = Node(7)root.right.right = Node(12)root.right.right.right = Node(15)Â Â Â print(maximumLengthAP(root))Â
# This code is contributed by decode2207. |
C#
// C# program for the above approachusing System;Â
class GFG{Â Â Â Â Â static int maxLength;Â Â Â Â Â Â Â Â // TreeNode classclass Node{Â Â Â Â public int val;Â Â Â Â public Node left, right;};Â
static Node newNode(int key){Â Â Â Â Node temp = new Node();Â Â Â Â temp.val = key;Â Â Â Â temp.left = temp.right = null;Â Â Â Â return temp;}Â
// Function to perform DFS Traversal// to find the maximum length of a path// to a bottom node forming an APstatic void dfs(Node root, int currentDifference,                int count){         // If the root's left child exists    if (root.left != null)     {                 // Calculate the difference        int difference = root.left.val - root.val;Â
        // If the difference is same        // as the current difference        if (difference == currentDifference)        {            dfs(root.left, currentDifference,                count + 1);Â
            // Update the maxLength            maxLength = Math.Max(maxLength,                                 count + 1);        }Â
        // Otherwise        else        {            dfs(root.left, difference, 2);        }    }Â
    // If the root's right child exists    if (root.right != null)    {                 // Find the difference        int difference = root.right.val - root.val;Â
        // If the difference is the same        // as the current difference        if (difference == currentDifference)        {            dfs(root.right, currentDifference,                count + 1);Â
            // Update the maxLength            maxLength = Math.Max(maxLength,                                 count + 1);        }Â
        // Otherwise        else        {            dfs(root.right, difference, 2);        }    }}Â
// Function to find the maximum length// of the path from any node to bottom// of the tree forming an APstatic int maximumLengthAP(Node root){         // Base Cases    if (root == null)        return 0;Â
    if (root.left == null &&         root.right == null)    {        return 1;    }Â
    // Stores the resultant    // maximum length of the path     maxLength = 2;Â
    // If the root's left child exists    if (root.left != null)    {        int difference = root.left.val - root.val;        dfs(root.left, difference, 2);    }Â
    // If the root's right child exists    if (root.right != null)    {        int difference = root.right.val - root.val;        dfs(root.right, difference, 2);    }Â
    // Return the maximum length obtained    return maxLength;}   Â
// Driver codepublic static void Main(String[] args){          // Given Tree    Node root = newNode(6);    root.right = newNode(9);    root.right.left = newNode(7);    root.right.right = newNode(12);    root.right.right.right = newNode(15);         Console.WriteLine(maximumLengthAP(root));}}Â
// This code is contributed by gauravrajput1 |
Javascript
<script>Â
    // JavaScript program for the above approach         let maxLength;           class Node    {        constructor(key) {           this.left = null;           this.right = null;           this.val = key;        }    }         function newNode(key)    {        let temp = new Node(key);        return temp;    }Â
    // Function to perform DFS Traversal    // to find the maximum length of a path    // to a bottom node forming an AP    function dfs(root, currentDifference, count)    {Â
        // If the root's left child exists        if (root.left != null)        {Â
            // Calculate the difference            let difference = root.left.val - root.val;Â
            // If the difference is same            // as the current difference            if (difference == currentDifference)            {                dfs(root.left, currentDifference,                    count + 1);Â
                // Update the maxLength                maxLength = Math.max(maxLength,                                     count + 1);            }Â
            // Otherwise            else            {                dfs(root.left, difference, 2);            }        }Â
        // If the root's right child exists        if (root.right != null)        {Â
            // Find the difference            let difference = root.right.val - root.val;Â
            // If the difference is the same            // as the current difference            if (difference == currentDifference)            {                dfs(root.right, currentDifference,                    count + 1);Â
                // Update the maxLength                maxLength = Math.max(maxLength,                                     count + 1);            }Â
            // Otherwise            else            {                dfs(root.right, difference, 2);            }        }    }Â
    // Function to find the maximum length    // of the path from any node to bottom    // of the tree forming an AP    function maximumLengthAP(root)    {Â
        // Base Cases        if (root == null)            return 0;Â
        if (root.left == null &&            root.right == null)        {            return 1;        }Â
        // Stores the resultant        // maximum length of the path         maxLength = 2;Â
        // If the root's left child exists        if (root.left != null)        {            let difference = root.left.val - root.val;            dfs(root.left, difference, 2);        }Â
        // If the root's right child exists        if (root.right != null)        {            let difference = root.right.val - root.val;            dfs(root.right, difference, 2);        }Â
        // Return the maximum length obtained        return maxLength;    }          // Given Tree    let root = newNode(6);    root.right = newNode(9);    root.right.left = newNode(7);    root.right.right = newNode(12);    root.right.right.right = newNode(15);          document.write(maximumLengthAP(root));     </script> |
4
Â
Time Complexity: O(N)
Auxiliary Space: O(1)
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

