Count of Fibonacci paths in a Binary tree

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++

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 reursive 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 fibonaci 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

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 reursive 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 fibonaci 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

chevron_right


Output:

2

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : 29AjayKumar, princi singh