Find the numbers present at Kth level of a Fibonacci Binary Tree
Last Updated :
10 Apr, 2023
Given a number K, the task is to print the fibonacci numbers present at Kth level of a Fibonacci Binary Tree.
Examples:
Input: K = 3
Output: 2, 3, 5, 8
Explanation:
Fibonacci Binary Tree for 3 levels:
0
/ \
1 1
/\ / \
2 3 5 8
Numbers present at level 3: 2, 3, 5, 8
Input: K = 2
Output: 1, 1
Explanation:
Fibonacci Binary Tree for 2 levels:
0
/ \
1 1
Numbers present at level 2: 1, 1
Naive Approach: The naive approach is to build a Fibonacci Binary Tree (binary tree of Fibonacci numbers) and then get elements at a particular level K.
However, this approach is obsolete for large numbers as it takes too much time.
Efficient approach: Since the elements which would be present at some arbitrary level K of the tree can be found by finding the elements in the range [2K – 1, 2K – 1]. Therefore:
- Find the Fibonacci numbers up to 106 using Dynamic Programming and store them in an array.
- Calculate the left_index and right_index of the level as:
left_index = 2K - 1
right_index = 2K - 1
- Print the fibonacci numbers from left_index to right_index of fibonacci array.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
#define MAX_SIZE 100005
int fib[MAX_SIZE + 1];
void fibonacci()
{
int i;
fib[0] = 0;
fib[1] = 1;
for (i = 2; i <= MAX_SIZE; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
}
void printLevel( int level)
{
int left_index = pow (2, level - 1);
int right_index = pow (2, level) - 1;
for ( int i = left_index;
i <= right_index; i++) {
cout << fib[i - 1] << " " ;
}
cout << endl;
}
int main()
{
fibonacci();
int K = 4;
printLevel(K);
return 0;
}
|
Java
import java.util.*;
class GFG{
static final int MAX_SIZE = 100005 ;
static int []fib = new int [MAX_SIZE + 1 ];
static void fibonacci()
{
int i;
fib[ 0 ] = 0 ;
fib[ 1 ] = 1 ;
for (i = 2 ; i <= MAX_SIZE; i++) {
fib[i] = fib[i - 1 ] + fib[i - 2 ];
}
}
static void printLevel( int level)
{
int left_index = ( int ) Math.pow( 2 , level - 1 );
int right_index = ( int ) (Math.pow( 2 , level) - 1 );
for ( int i = left_index;
i <= right_index; i++) {
System.out.print(fib[i - 1 ]+ " " );
}
System.out.println();
}
public static void main(String[] args)
{
fibonacci();
int K = 4 ;
printLevel(K);
}
}
|
Python3
MAX_SIZE = 100005
fib = [ 0 ] * (MAX_SIZE + 1 )
def fibonacci():
fib[ 0 ] = 0
fib[ 1 ] = 1
for i in range ( 2 , MAX_SIZE + 1 ):
fib[i] = fib[i - 1 ] + fib[i - 2 ]
def printLevel(level):
left_index = pow ( 2 , level - 1 )
right_index = pow ( 2 , level) - 1
for i in range (left_index, right_index + 1 ):
print (fib[i - 1 ],end = " " )
print ()
fibonacci()
K = 4
printLevel(K)
|
C#
using System;
class GFG{
static int MAX_SIZE = 100005;
static int []fib = new int [MAX_SIZE + 1];
static void fibonacci()
{
int i;
fib[0] = 0;
fib[1] = 1;
for (i = 2; i <= MAX_SIZE; i++) {
fib[i] = fib[i - 1] + fib[i - 2];
}
}
static void printLevel( int level)
{
int left_index = ( int ) Math.Pow(2, level - 1);
int right_index = ( int ) (Math.Pow(2, level) - 1);
for ( int i = left_index;
i <= right_index; i++) {
Console.Write(fib[i - 1]+ " " );
}
Console.WriteLine();
}
public static void Main( string [] args)
{
fibonacci();
int K = 4;
printLevel(K);
}
}
|
Javascript
<script>
var MAX_SIZE = 100005;
var fib = Array(MAX_SIZE + 1).fill(0);
function fibonacci()
{
var i;
fib[0] = 0;
fib[1] = 1;
for (i = 2; i <= MAX_SIZE; i++)
{
fib[i] = fib[i - 1] + fib[i - 2];
}
}
function printLevel(level)
{
var left_index =
parseInt( Math.pow(2, level - 1));
var right_index =
parseInt( (Math.pow(2, level) - 1));
for (i = left_index; i <= right_index; i++)
{
document.write(fib[i - 1] + " " );
}
document.write();
}
fibonacci();
var K = 4;
printLevel(K);
</script>
|
Output:
13 21 34 55 89 144 233 377
Time complexity : O(MAX_SIZE)
Auxiliary space : O(MAX_SIZE)
Efficient approach :
Space optimization O(1)
In previous approach the fib[i] is depend upon fib[i-1] and fib[i-2] So to calculate the current value we just need two previous values. In this approach we replace fib[i-1] to prev1 and fib[i-2] to prev2 and fib[i] to curr.
Steps that were to follow this approach:
- Initialize variables prev1, prev2 and curr to keep track of previous two values and current value.
- Set base cases of prev1 and prev2.
- Iterate over subproblems and get the current value and store in curr.
- After every iteration store prev2 to prev1 and curr to prev2 to iterate further.
- At last iterate every computation and print curr.
Below is the code to implement the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void printFibonacciLevel( int level) {
int prev1 = 0, prev2 = 1;
int curr;
int left_index = pow (2, level - 1);
for ( int i = 1; i <= left_index; i++) {
if (i <= 2) {
curr = i - 1;
} else {
curr = prev1 + prev2;
prev1 = prev2;
prev2 = curr;
}
}
int right_index = pow (2, level) - 2;
for ( int i = left_index; i <= right_index+1; i++) {
cout << curr << " " ;
if (i <= 2) {
curr = i - 1;
} else {
curr = prev1 + prev2;
prev1 = prev2;
prev2 = curr;
}
}
cout << endl;
}
int main() {
int K = 4;
printFibonacciLevel(K);
return 0;
}
|
Java
import java.util.*;
class GFG {
static void printFibonacciLevel( int level) {
int prev1 = 0 , prev2 = 1 ;
int curr = 0 ;
int left_index = ( int ) Math.pow( 2 , level - 1 );
for ( int i = 1 ; i <= left_index; i++) {
if (i <= 2 ) {
curr = i - 1 ;
} else {
curr = prev1 + prev2;
prev1 = prev2;
prev2 = curr;
}
}
int right_index = ( int ) Math.pow( 2 , level) - 2 ;
for ( int i = left_index; i <= right_index+ 1 ; i++) {
System.out.print(curr + " " );
if (i <= 2 ) {
curr = i - 1 ;
} else {
curr = prev1 + prev2;
prev1 = prev2;
prev2 = curr;
}
}
System.out.println();
}
public static void main(String[] args) {
int K = 4 ;
printFibonacciLevel(K);
}
}
|
Python3
import math
def printFibonacciLevel(level):
prev1 = 0
prev2 = 1
curr = 0
left_index = int (math. pow ( 2 , level - 1 ))
for i in range ( 1 , left_index + 1 ):
if i < = 2 :
curr = i - 1
else :
curr = prev1 + prev2
prev1 = prev2
prev2 = curr
right_index = int (math. pow ( 2 , level)) - 2
for i in range (left_index, right_index + 2 ):
print (curr, end = " " )
if i < = 2 :
curr = i - 1
else :
curr = prev1 + prev2
prev1 = prev2
prev2 = curr
print ()
if __name__ = = '__main__' :
K = 4
printFibonacciLevel(K)
|
C#
using System;
class GFG
{
static void PrintFibonacciLevel( int level)
{
int prev1 = 0, prev2 = 1;
int curr = 0;
int left_index = ( int )Math.Pow(2, level - 1);
for ( int i = 1; i <= left_index; i++)
{
if (i <= 2)
{
curr = i - 1;
}
else
{
curr = prev1 + prev2;
prev1 = prev2;
prev2 = curr;
}
}
int right_index = ( int )Math.Pow(2, level) - 2;
for ( int i = left_index; i <= right_index + 1; i++)
{
Console.Write(curr + " " );
if (i <= 2)
{
curr = i - 1;
}
else
{
curr = prev1 + prev2;
prev1 = prev2;
prev2 = curr;
}
}
Console.WriteLine();
}
static void Main( string [] args)
{
int K = 4;
PrintFibonacciLevel(K);
}
}
|
Javascript
function printFibonacciLevel(level) {
let prev1 = 0, prev2 = 1;
let curr;
let left_index = Math.pow(2, level - 1);
for (let i = 1; i <= left_index; i++) {
if (i <= 2) {
curr = i - 1;
}
else {
curr = prev1 + prev2;
prev1 = prev2;
prev2 = curr;
}
}
let right_index = Math.pow(2, level) - 2;
let ans = "" ;
for (let i = left_index; i <= right_index + 1; i++) {
ans += curr;
ans += " " ;
if (i <= 2) {
curr = i - 1;
}
else {
curr = prev1 + prev2;
prev1 = prev2;
prev2 = curr;
}
}
console.log(ans);
}
let K = 4;
printFibonacciLevel(K);
|
Output:
13 21 34 55 89 144 233 377
Time complexity: O(2^K) because we need to compute the Fibonacci numbers at each level of the binary tree up to level K
Auxiliary space : O(1)
Similar Reads
Print all Nodes of given Binary Tree at the Kth Level
Given a binary tree and an integer K, the task is to print all the integers at the Kth level in the tree from left to right. Examples: Input: Tree in the image below, K = 3 Output: 4 5 6Explanation: All the nodes present in level 3 of above binary tree from left to right are 4, 5, and 6. Input: Tree
5 min read
Sum of numbers in the Kth level of a Fibonacci triangle
Given a number K, the task is to find the sum of numbers at the Kth level of the Fibonacci triangle.Examples: Input: K = 3 Output: 10 Explanation: Fibonacci triangle till level 3: 0 1 1 2 3 5 Sum at 3rd level = 2 + 3 + 5 = 10 Input: K = 2 Output: 2 Explanation: Fibonacci triangle till level 3: 0 1 1
6 min read
Sum of all nodes at Kth level in a Binary Tree
Given a binary tree with N nodes and an integer K, the task is to find the sum of all the nodes present at the Kth level. Examples: Input: K = 1 Output: 70 Input: K = 2 Output: 120 Approach: Traverse the Binary Tree using Level Order Traversal and queueDuring traversal, pop each element out of the q
15+ min read
Print the number of set bits in each node of a Binary Tree
Given a Binary Tree. The task is to print the number of set bits in each of the nodes in the Binary Tree. The idea is to traverse the given binary tree using any tree traversal method, and for each node calculate the number of set bits and print it. Note: One can also use the __builtin_popcount() fu
6 min read
Print Levels of all nodes in a Binary Tree
Given a Binary Tree and a key, write a function that prints levels of all keys in given binary tree. For example, consider the following tree. If the input key is 3, then your function should return 1. If the input key is 4, then your function should return 3. And for key which is not present in key
7 min read
Count the Number of Binary Search Trees present in a Binary Tree
Given a binary tree, the task is to count the number of Binary Search Trees present in it. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: 4Here each leaf node represents a binary search tree and there are total 4 nodes. Input: 11 / \ 8 10 / / \ 5 9 8 / \ 4 6 Output: 6 Sub-tree rooted under node
10 min read
Print the middle nodes of each level of a Binary Tree
Given a Binary Tree, the task is to print the middle nodes of each level of a binary tree. Considering M to be the number of nodes at any level, print (M/2)th node if M is odd. Otherwise, print (M/2)th node and ((M/2) + 1)th node. Examples: Input: Below is the given Tree: Output:12 35 1011 67 9Expla
11 min read
Find the maximum node at a given level in a binary tree
Given a Binary Tree and a Level. The task is to find the node with the maximum value at that given level. The idea is to traverse the tree along depth recursively and return the nodes once the required level is reached and then return the maximum of left and right subtrees for each subsequent call.
13 min read
Print all nodes in a binary tree having K leaves
Given a binary tree and a integer value K, the task is to find all nodes in given binary tree having K leaves in subtree rooted with them. Examples : // For above binary tree Input : k = 2 Output: {3} // here node 3 have k = 2 leaves Input : k = 1 Output: {6} // here node 6 have k = 1 leaveRecommend
7 min read
Nodes at Kth level without duplicates in a Binary Tree
Given a binary tree with N nodes and an integer K, the task is to print nodes of the Kth level of a binary tree without duplicates. Examples: Input: 60 --- Level 0 / \ 50 30 --- Level 1 / \ / 80 10 40 --- Level 2 K = 1 Output: 30 50 Input: 50 --- Level 0 / \ 60 70 --- Level 1 / \ / \ 90 40 40 20 ---
11 min read