Related Articles

# Longest path to the bottom of a Binary Tree forming an Arithmetic Progression

• Difficulty Level : Medium
• Last Updated : 01 Jul, 2021

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 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 Node``struct` `Tree {``    ``int` `val;``    ``Tree *left, *right;``};` `// Function to create a new node``Tree* 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 AP``void` `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 AP``int` `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 Code``int` `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 approach``import` `java.lang.*;``import` `java.util.*;` `class` `GFG{``    ` `static` `int` `maxLength;   ``    ` `// TreeNode class``static` `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 AP``static` `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 AP``static` `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 code``public` `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`

## Javascript

 ``
Output:
`4`

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.

My Personal Notes arrow_drop_up