Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Program to count leaf nodes in a binary tree
Next article icon

Count of Fibonacci paths in a Binary tree

Last Updated : 01 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

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: 

C++




// C++ program to count all of
// Fibonacci paths in a Binary tree
 
#include <bits/stdc++.h>
using namespace std;
 
// Vector to store the fibonacci series
vector<int> fib;
 
// Binary Tree Node
struct node {
    struct node* left;
    int data;
    struct node* right;
};
 
// Function to create a new tree node
node* newNode(int data)
{
    node* temp = new node;
    temp->data = data;
    temp->left = NULL;
    temp->right = NULL;
    return temp;
}
 
// Function to find the height
// of the given tree
int height(node* root)
{
    int ht = 0;
    if (root == NULL)
        return 0;
 
    return (max(height(root->left),
                height(root->right))
            + 1);
}
 
// Function to make fibonacci series
// upto n terms
void FibonacciSeries(int n)
{
    fib.push_back(0);
    fib.push_back(1);
    for (int i = 2; i < n; i++)
        fib.push_back(fib[i - 1]
                      + fib[i - 2]);
}
 
// Preorder Utility function to count
// exponent path in a given Binary tree
int CountPathUtil(node* root,
                  int i, int count)
{
 
    // Base Condition, when node pointer
    // becomes null or node value is not
    // a number of pow(x, y )
    if (root == NULL
        || !(fib[i] == root->data)) {
        return count;
    }
 
    // Increment count when
    // encounter leaf node
    if (!root->left
        && !root->right) {
        count++;
    }
 
    // Left recursive call
    // save the value of count
    count = CountPathUtil(
        root->left, i + 1, count);
 
    // Right recursive call and
    // return value of count
    return CountPathUtil(
        root->right, i + 1, count);
}
 
// Function to find whether
// fibonacci path exists or not
void CountPath(node* root)
{
    // To find the height
    int ht = height(root);
 
    // Making fibonacci series
    // upto ht terms
    FibonacciSeries(ht);
 
    cout << CountPathUtil(root, 0, 0);
}
 
// Driver code
int main()
{
    // Create binary tree
    node* root = newNode(0);
 
    root->left = newNode(1);
    root->right = newNode(1);
 
    root->left->left = newNode(1);
    root->left->right = newNode(4);
    root->right->right = newNode(1);
    root->right->right->left = newNode(2);
 
    // Function Call
    CountPath(root);
 
    return 0;
}
 
 

Java




// Java program to count all of
// Fibonacci paths in a Binary tree
import java.util.*;
 
class GFG{
 
// Vector to store the fibonacci series
static Vector<Integer> fib = new Vector<Integer>();
 
// Binary Tree Node
static class node {
    node left;
    int data;
    node right;
};
 
// Function to create a new tree node
static node newNode(int data)
{
    node temp = new node();
    temp.data = data;
    temp.left = null;
    temp.right = null;
    return temp;
}
 
// Function to find the height
// of the given tree
static int height(node root)
{
    if (root == null)
        return 0;
 
    return (Math.max(height(root.left),
                height(root.right))
            + 1);
}
 
// Function to make fibonacci series
// upto n terms
static void FibonacciSeries(int n)
{
    fib.add(0);
    fib.add(1);
    for (int i = 2; i < n; i++)
        fib.add(fib.get(i - 1)
                    + fib.get(i - 2));
}
 
// Preorder Utility function to count
// exponent path in a given Binary tree
static int CountPathUtil(node root,
                int i, int count)
{
 
    // Base Condition, when node pointer
    // becomes null or node value is not
    // a number of Math.pow(x, y )
    if (root == null
        || !(fib.get(i) == root.data)) {
        return count;
    }
 
    // Increment count when
    // encounter leaf node
    if (root.left != null
        && root.right != null) {
        count++;
    }
 
    // Left recursive call
    // save the value of count
    count = CountPathUtil(
        root.left, i + 1, count);
 
    // Right recursive call and
    // return value of count
    return CountPathUtil(
        root.right, i + 1, count);
}
 
// Function to find whether
// fibonacci path exists or not
static void CountPath(node root)
{
    // To find the height
    int ht = height(root);
 
    // Making fibonacci series
    // upto ht terms
    FibonacciSeries(ht);
 
    System.out.print(CountPathUtil(root, 0, 0));
}
 
// Driver code
public static void main(String[] args)
{
    // Create binary tree
    node root = newNode(0);
 
    root.left = newNode(1);
    root.right = newNode(1);
 
    root.left.left = newNode(1);
    root.left.right = newNode(4);
    root.right.right = newNode(1);
    root.right.right.left = newNode(2);
 
    // Function Call
    CountPath(root);
 
}
}
 
// This code is contributed by 29AjayKumar
 
 

Python3




# Python3 program to count all of
# Fibonacci paths in a Binary tree
  
# Vector to store the fibonacci series
fib = []
  
# Binary Tree Node
class node:
     
    def __init__(self, data):
         
        self.data = data
        self.left = None
        self.right = None
  
# Function to create a new tree node
def newNode(data):
 
    temp = node(data)
    return temp
  
# Function to find the height
# of the given tree
def height(root):
 
    ht = 0
     
    if (root == None):
        return 0
  
    return (max(height(root.left),
                height(root.right)) + 1)
 
# Function to make fibonacci series
# upto n terms
def FibonacciSeries(n):
 
    fib.append(0)
    fib.append(1)
     
    for i in range(2, n):
        fib.append(fib[i - 1] + fib[i - 2])
 
# Preorder Utility function to count
# exponent path in a given Binary tree
def CountPathUtil(root, i, count):
  
    # Base Condition, when node pointer
    # becomes null or node value is not
    # a number of pow(x, y )
    if (root == None or not (fib[i] == root.data)):
        return count
     
    # Increment count when
    # encounter leaf node
    if (not root.left and not root.right):
        count += 1
  
    # Left recursive call
    # save the value of count
    count = CountPathUtil(root.left, i + 1, count)
  
    # Right recursive call and
    # return value of count
    return CountPathUtil(root.right, i + 1, count)
 
# Function to find whether
# fibonacci path exists or not
def CountPath(root):
 
    # To find the height
    ht = height(root)
  
    # Making fibonacci series
    # upto ht terms
    FibonacciSeries(ht)
     
    print(CountPathUtil(root, 0, 0))
 
# Driver code
if __name__=='__main__':
 
    # Create binary tree
    root = newNode(0)
  
    root.left = newNode(1)
    root.right = newNode(1)
  
    root.left.left = newNode(1)
    root.left.right = newNode(4)
    root.right.right = newNode(1)
    root.right.right.left = newNode(2)
  
    # Function Call
    CountPath(root)
  
# This code is contributed by rutvik_56
 
 

C#




// C# program to count all of
// Fibonacci paths in a Binary tree
using System;
using System.Collections.Generic;
 
class GFG{
  
// List to store the fibonacci series
static List<int> fib = new List<int>();
  
// Binary Tree Node
class node {
    public node left;
    public int data;
    public node right;
};
  
// Function to create a new tree node
static node newNode(int data)
{
    node temp = new node();
    temp.data = data;
    temp.left = null;
    temp.right = null;
    return temp;
}
  
// Function to find the height
// of the given tree
static int height(node root)
{
    if (root == null)
        return 0;
  
    return (Math.Max(height(root.left),
                height(root.right))
            + 1);
}
  
// Function to make fibonacci series
// upto n terms
static void FibonacciSeries(int n)
{
    fib.Add(0);
    fib.Add(1);
    for (int i = 2; i < n; i++)
        fib.Add(fib[i - 1]
                    + fib[i - 2]);
}
  
// Preorder Utility function to count
// exponent path in a given Binary tree
static int CountPathUtil(node root,
                int i, int count)
{
  
    // Base Condition, when node pointer
    // becomes null or node value is not
    // a number of Math.Pow(x, y)
    if (root == null
        || !(fib[i] == root.data)) {
        return count;
    }
  
    // Increment count when
    // encounter leaf node
    if (root.left != null
        && root.right != null) {
        count++;
    }
  
    // Left recursive call
    // save the value of count
    count = CountPathUtil(
        root.left, i + 1, count);
  
    // Right recursive call and
    // return value of count
    return CountPathUtil(
        root.right, i + 1, count);
}
  
// Function to find whether
// fibonacci path exists or not
static void CountPath(node root)
{
    // To find the height
    int ht = height(root);
  
    // Making fibonacci series
    // upto ht terms
    FibonacciSeries(ht);
  
    Console.Write(CountPathUtil(root, 0, 0));
}
  
// Driver code
public static void Main(String[] args)
{
    // Create binary tree
    node root = newNode(0);
  
    root.left = newNode(1);
    root.right = newNode(1);
  
    root.left.left = newNode(1);
    root.left.right = newNode(4);
    root.right.right = newNode(1);
    root.right.right.left = newNode(2);
  
    // Function Call
    CountPath(root);
}
}
 
// This code is contributed by Princi Singh
 
 

Javascript




<script>
 
    // JavaScript program to count all of
    // Fibonacci paths in a Binary tree
     
    // Vector to store the fibonacci series
    let fib = [];
 
    // Binary Tree Node
    class node {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    };
 
    // Function to create a new tree node
    function newNode(data)
    {
        let temp = new node(data);
        return temp;
    }
 
    // Function to find the height
    // of the given tree
    function height(root)
    {
        if (root == null)
            return 0;
 
        return (Math.max(height(root.left),
                    height(root.right))
                + 1);
    }
 
    // Function to make fibonacci series
    // upto n terms
    function FibonacciSeries(n)
    {
        fib.push(0);
        fib.push(1);
        for (let i = 2; i < n; i++)
            fib.push(fib[i - 1] + fib[i - 2]);
    }
 
    // Preorder Utility function to count
    // exponent path in a given Binary tree
    function CountPathUtil(root, i, count)
    {
 
        // Base Condition, when node pointer
        // becomes null or node value is not
        // a number of Math.pow(x, y )
        if (root == null
            || !(fib[i] == root.data)) {
            return count;
        }
 
        // Increment count when
        // encounter leaf node
        if (root.left != null
            && root.right != null) {
            count++;
        }
 
        // Left recursive call
        // save the value of count
        count = CountPathUtil(root.left, i + 1, count);
 
        // Right recursive call and
        // return value of count
        return CountPathUtil(root.right, i + 1, count);
    }
 
    // Function to find whether
    // fibonacci path exists or not
    function CountPath(root)
    {
        // To find the height
        let ht = height(root);
 
        // Making fibonacci series
        // upto ht terms
        FibonacciSeries(ht);
 
        document.write(CountPathUtil(root, 0, 0));
    }
     
    // Create binary tree
    let root = newNode(0);
  
    root.left = newNode(1);
    root.right = newNode(1);
  
    root.left.left = newNode(1);
    root.left.right = newNode(4);
    root.right.right = newNode(1);
    root.right.right.left = newNode(2);
  
    // Function Call
    CountPath(root);
   
</script>
 
 
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.



Next Article
Program to count leaf nodes in a binary tree
author
chsadik99
Improve
Article Tags :
  • Arrays
  • DSA
  • Dynamic Programming
  • Recursion
  • Tree
  • Fibonacci
  • Preorder Traversal
Practice Tags :
  • Arrays
  • Dynamic Programming
  • Fibonacci
  • Recursion
  • Tree

Similar Reads

  • Count of exponential paths in a Binary Tree
    Given a Binary Tree, the task is to count the number of Exponential paths in the given Binary Tree. Exponential Path is a path where root to leaf path contains all nodes being equal to xy, & where x is a minimum possible positive constant & y is a variable positive integer. Example: Input: 2
    11 min read
  • Count of 1's in any path in a Binary Tree
    Given a binary tree of 0s and 1s, the task is to find the maximum number of 1s in any path in the tree. The path may start and end at any node in the tree.Example: Input: 1 / \ 0 1 / \ 1 1 / \ 1 0 Output: 4 Approach: A function countUntil has been created which returns the maximum count of 1 in any
    10 min read
  • Count even paths in Binary Tree
    Given a Binary Tree, the task is to count the number of even paths in the given Binary Tree. Even Path is a path where root to leaf path contains all even nodes only. Examples: Input: Below is the given Binary Tree: Output: 3 Explanation: There are 3 even path for the above Binary Tree: 1. 10->12
    8 min read
  • Count all K Sum Paths in Binary Tree
    Given a binary tree and an integer k, the task is to count the number of paths in the tree such that the sum of the nodes in each path equals k. A path can start from any node and end at any node and must be downward only. Examples: Input: k = 7 Output: 3 Table of Content [Naive Approach] By Explori
    15+ min read
  • Program to count leaf nodes in a binary tree
    Given a Binary Tree, the task is to count leaves in it. A node is a leaf node if both left and right child nodes of it are NULL. Example: Input: Output: 3Explanation: Three leaf nodes are 3, 4 and 5 as both of their left and right child is NULL.Input: Output: 3Explanation: Three leaf nodes are 4, 6
    7 min read
  • Count Non-Leaf nodes in a Binary Tree
    Given a Binary tree, count the total number of non-leaf nodes in the tree Examples: Input : Output :2 Explanation In the above tree only two nodes 1 and 2 are non-leaf nodesRecommended PracticeCount Non-Leaf Nodes in TreeTry It! We recursively traverse the given tree. While traversing, we count non-
    10 min read
  • Count frequency of K in given Binary Tree
    Given a binary tree of N nodes. Count the frequency of an integer K in the binary tree. Examples: Input: N = 7, K = 2 1 / \ 2 3 / \ / \4 2 2 5Output: 3Explanation: 2 occurs 3 times in the tree. Input: N = 6, K = 5 1 / \ 4 5 / \ / \5 6 2 4Output: 2Explanation: 5 occurs 2 times in the tree. Approach:
    14 min read
  • Count of root to leaf paths in a Binary Tree that form an AP
    Given a Binary Tree, the task is to count all paths from root to leaf which forms an Arithmetic Progression. Examples: Input: Output: 2 Explanation: The paths that form an AP in the given tree from root to leaf are: 1->3->5 (A.P. with common difference 2)1->6->11 (A.P. with common differ
    7 min read
  • Count of Simple Paths in given Tree
    Given a tree of N nodes numbered from 1 to N and N-1 edges, and an array V[] of length N denoting the value of the ith node (0 ? i ? n-1). The task is to calculate the number of simple paths starting with node 1. A path is defined as a simple path if the frequency of the value of any one of the node
    8 min read
  • Count of duplicate Subtrees in an N-ary Tree
    Given the root of an n-ary tree, the task is to find the number of subtrees that have duplicates in the n-ary tree. Two trees are duplicates if they have the same structure with the same node values. Examples: Input: 1 N 2 2 3 N 4 N 4 4 3 N N N N NOutput: 2Explanation: [4], [3] are duplicate subtree
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences