Number of leaf nodes in a perfect N-ary tree of height K
Find the number of leaf nodes in a perfect N-ary tree of height K.
Note: As the answer can be very large, return the answer modulo 109+7.
Examples:
Input: N = 2, K = 2
Output: 4
Explanation: A perfect Binary tree of height 2 has 4 leaf nodes.
Input: N = 2, K = 1
Output: 2
Explanation: A perfect Binary tree of height 1 has 2 leaf nodes.
Approach: This problem can be solved based on the observation that the number of leaf nodes in a perfect N-ary tree with height K will be equal to NK. Use Modular exponentiation to calculate the power modulo 109+7.
Follow the steps mentioned below to implement the above idea.
- Initialize one variable res = 1.
- Keep on reducing the power (here K) by half and squaring the base (here N) until the power is positive.
- Also when the power is odd, multiply the result by the base.
- Take mod 109+7 in each step.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
long long karyTree( long long N, int K)
{
long long res = 1;
while (K > 0) {
if (K & 1)
res = (res * N) % mod;
N = (N * N) % mod;
K >>= 1;
}
return res;
}
int main()
{
int N = 2, K = 2;
cout << karyTree(N, K);
return 0;
}
|
Java
import java.io.*;
class GFG {
static final int mod = 1000000007 ;
public static void main(String[] args)
{
int N = 2 , K = 2 ;
System.out.println(karyTree(N, K));
}
public static long karyTree( long N, int K)
{
long res = 1 ;
while (K > 0 ) {
if (K % 2 == 1 )
res = (res * N) % mod;
N = (N * N) % mod;
K >>= 1 ;
}
return res;
}
}
|
Python3
mod = 1e9 + 7
def karyTree(N, K):
res = 1
while (K > 0 ):
if (K & 1 ):
res = (res * N) % mod
N = (N * N) % mod
K >> = 1
return res
N,K = 2 , 2
print (karyTree(N, K))
|
C#
using System;
class GFG {
static int mod = 1000000007;
public static void Main()
{
int N = 2, K = 2;
Console.Write(karyTree(N, K));
}
static long karyTree( long N, int K)
{
long res = 1;
while (K > 0) {
if (K % 2 == 1)
res = (res * N) % mod;
N = (N * N) % mod;
K >>= 1;
}
return res;
}
}
|
Javascript
<script>
const mod = 1e9 + 7;
function karyTree(N, K)
{
let res = 1;
while (K > 0) {
if (K & 1)
res = (res * N) % mod;
N = (N * N) % mod;
K >>= 1;
}
return res;
}
let N = 2, K = 2;
document.write(karyTree(N, K));
</script>
|
Time Complexity: O(logK)
Auxiliary Space: O(1)
Last Updated :
04 May, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...