VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-of-fibonacci-paths-in-a-binary-tree/

⇱ Count of Fibonacci paths in a Binary tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of Fibonacci paths in a Binary tree

Last Updated : 12 Jul, 2025

Given a Binary Tree, the task is to count the number of Fibonacci paths in the given Binary Tree. 

Fibonacci Path is a path which contains all nodes in root to leaf path are terms of Fibonacci series.

Example: 

Input:
 0
 / \
 1 1
 / \ / \
 1 10 70 1
 / \
 81 2
Output: 2 
Explanation:
There are 2 Fibonacci path for
the above Binary Tree, for x = 3,
Path 1: 0 1 1
Path 2: 0 1 1 2

Input:
 8
 / \
 4 81
 / \ / \
 3 2 70 243
 / \
 81 909
Output: 0

Approach: The idea is to use Preorder Tree Traversal. During preorder traversal of the given binary tree do the following:  

  1. First calculate the Height of binary tree .
  2. Now create a vector of length equals height of tree, such that it contains Fibonacci Numbers.
  3. If current value of the node at ith level is not equal to ith term of fibonacci series or pointer becomes NULL then return the count.
  4. If the current node is a leaf node then increment the count by 1.
  5. Recursively call for the left and right subtree with the updated count.
  6. After all-recursive call, the value of count is number of Fibonacci paths for a given binary tree.

Below is the implementation of the above approach: 


Output: 
2

 

Time Complexity: O(n), where n is the number of nodes in the given tree.
Auxiliary Space: O(h), where h is the height of the tree.

Comment