// 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;
}