Given a binary tree, the task is to find the length of the longest path which forms an Arithmetic progression. The path can start and end at any node of the tree.
Examples:
Input:
👁 Image
Output: 5
Explanation: The longest path forming an AP is: 3->6->9->12->15
Input:
👁 Image
Output: 6
Explanation: The longest path forming an AP is: 2->4->6->8->10->12
Approach: The catch here is that a tree node can only support two AP's, one with the left child and the other one with the right child. Now, to solve this problem, follow the below steps:
- Create a variable ans to store the length of the longest path.
- Start a depth-first search from the root node, and for each node, find the maximum length path of AP's till left child and right child.
- Now find the difference between the current node and its left child, say leftDiff and the difference between the current node and its right child, say rightDiff.
- Now find the longest path with difference leftDiff in the left child, say maxLen1 and longest path with difference rightDiff in the right child, say maxLen2.
- If leftDiff = (-1)*rightDiff, then both the branches of the current node form an AP, so change ans to the maximum out of the previous value of ans and maxLen1+maxLen2+1.
- Else, change ans to the maximum out of the previous value of ans, (maxLen1+1) and (maxLen2+1), because only one of the two paths can be selected.
- Now return maxLen1 and maxLen2 along with the difference of the AP from the current node to the parent node.
- Print ans after the function stops.
Below is the implementation of the above approach:
Time Complexity: O(N) where N is number of nodes in the Tree
Auxiliary Space: O(N)