给定‘N’和‘I’的值。这里, 表示N元树中存在的内部节点的数量,并且N元的每个节点都可以具有个孩子或零个孩子。任务是确定n元树中的Leaf节点数。
例子:
Input : N = 3, I = 5
Output : Leaf nodes = 11
Input : N = 10, I = 10
Output : leaf nodes = 91
公式:
where,
I = Number of Internal nodes.
L = Leaf Nodes.
and, N = Number of children each node can have.
派生:该树是N元树。假设它有T个总节点,这是内部节点(I)和叶节点(L)的总和。总节点数为T的树将具有(T – 1)个边或分支。
换句话说,由于树是N元树,因此每个内部节点将具有N个分支,这些分支总共贡献了N * I个内部分支。因此,根据上述说明,我们具有以下关系:
- N * I = T – 1
- L + I = T
从以上两个方程式,我们可以说L =(N – 1)* I + 1。
下面是上述方法的实现:
C++
// CPP program to find number
// of leaf nodes
#include
using namespace std;
// Function to calculate
// leaf nodes in n-ary tree
int calcNodes(int N, int I)
{
int result = 0;
result = I * (N - 1) + 1;
return result;
}
// Driver code
int main()
{
int N = 5, I = 2;
cout << "Leaf nodes = " << calcNodes(N, I);
return 0;
}
Java
// Java program to find number
// of leaf nodes
class GfG
{
// Function to calculate
// leaf nodes in n-ary tree
static int calcNodes(int N, int I)
{
int result = 0;
result = I * (N - 1) + 1;
return result;
}
// Driver code
public static void main(String[] args)
{
int N = 5, I = 2;
System.out.println("Leaf nodes = " +
calcNodes(N, I));
}
}
// This code is contributed by Prerna Saini
Python3
# Python3 program to find number
# of leaf nodes
# Function to calculate
# leaf nodes in n-ary tree
def calcNodes(N, I):
result = 0
result = I * (N - 1) + 1
return result
# Driver Code
if __name__ == '__main__':
N = 5
I = 2
print("Leaf nodes = ",
calcNodes(N, I))
# This code is contributed
# by SHUBHAMSINGH10
C#
// C# program to find number
// of leaf nodes
using System;
class GFG
{
// Function to calculate
// leaf nodes in n-ary tree
static int calcNodes(int N, int I)
{
int result = 0;
result = I * (N - 1) + 1;
return result;
}
// Driver code
public static void Main()
{
int N = 5, I = 2;
Console.Write("Leaf nodes = " +
calcNodes(N, I));
}
}
// This code is contributed
// by Akanksha Rai
PHP
Javascript
输出:
Leaf nodes = 9