Given a Binary Tree, the task is to output the Count of the number of paths formed by only a Triangular number. Xth Triangular number is the sum of the first X natural numbers. Example: {1, 3, 6, 10 . . .} are triangular numbers.
Explanation: There are 2 paths formed by only Triangular number which are {1 → 3 → 6} and {1 → 3 → 6 → 10}.
Approach: Implement the idea below to solve the problem
The idea to solve this problem is to generate a sequence of Triangular numbers based on the height of the tree and then traversing the tree in a Preorder traversal to identify paths that match this sequence.
Follow the steps to solve the problem:
Calculates the height of the tree recursively.
Initializes the Triangular number sequence based on the height of the tree to count the paths satisfying the condition.
In Preorder traversal, If the current node is NULL or if the node's value does not match the triangular number at the current node, then:
Return the current count as it is.
If it is a leaf node
Increment the count of paths.
Recursively call for the left and right subtree with the updated count.
After all-recursive call, the value of Count is number of triangular number paths for a given binary tree.
Below is the code to implement the above approach:
Output
1
Time Complexity: O(N), Where N is the number of nodes in the given tree. Auxiliary Complexity: O(H), Where H is the height of the tree.