📌  相关文章
📜  查找给定完美二叉树的所有节点的总和

📅  最后修改于: 2022-05-13 01:57:18.222000             🧑  作者: Mango

查找给定完美二叉树的所有节点的总和

给定一个正整数 L,它表示完美二叉树的层数。假设这棵完美二叉树中的叶子节点从 1 到 n 编号,其中 n 是叶子节点的数量。父节点是两个子节点的总和。我们的任务是编写一个程序来打印这棵完美二叉树的所有节点的总和。
例子:

Input : L = 3
Output : 30
Explanation : Tree will be - 10
                            /   \
                           3     7
                          /  \  /  \
                         1   2  3   4

Input : L = 2
Output : 6
Explanation : Tree will be -  3
                            /   \
                           1     2

朴素方法:最简单的解决方案是首先生成完美二叉树的所有节点的值,然后计算所有节点的总和。我们可以首先生成所有叶节点,然后以自下而上的方式继续生成其余节点。我们知道,在完美二叉树中,叶子节点的数量可以由 2 L-1给出,其中 L 是层数。当我们从底部向上移动时,完美二叉树中的节点数将减少一半。
下面是上述想法的实现:

C++
#include 
using namespace std;
 
// function to find sum of all of the nodes
// of given perfect binary tree
int sumNodes(int l)
{
    // no of leaf nodes
    int leafNodeCount = pow(2, l - 1);
 
    // list of vector to store nodes of
    // all of the levels
    vector vec[l];
 
    // store the nodes of last level
    // i.e., the leaf nodes
    for (int i = 1; i <= leafNodeCount; i++)
        vec[l - 1].push_back(i);
 
    // store nodes of rest of the level
    // by moving in bottom-up manner
    for (int i = l - 2; i >= 0; i--) {
        int k = 0;
 
        // loop to calculate values of parent nodes
        // from the children nodes of lower level
        while (k < vec[i + 1].size() - 1) {
 
            // store the value of parent node as
            // sum of children nodes
            vec[i].push_back(vec[i + 1][k] +
                             vec[i + 1][k + 1]);
            k += 2;
        }
    }
 
    int sum = 0;
 
    // traverse the list of vector
    // and calculate the sum
    for (int i = 0; i < l; i++) {
        for (int j = 0; j < vec[i].size(); j++)
            sum += vec[i][j];
    }
 
    return sum;
}
 
// Driver Code
int main()
{
    int l = 3;
 
    cout << sumNodes(l);
 
    return 0;
}


Java
// Java program to implement
// the above approach
import java.util.*;
class GFG
{
 
// function to find sum of
// all of the nodes of given
// perfect binary tree
static int sumNodes(int l)
{
    // no of leaf nodes
    int leafNodeCount = (int)Math.pow(2, l - 1);
 
    // list of vector to store
    // nodes of all of the levels
    Vector> vec = new Vector>();
     
    //initialize
    for (int i = 1; i <= l; i++)
    vec.add(new Vector());
     
    // store the nodes of last level
    // i.e., the leaf nodes
    for (int i = 1;
             i <= leafNodeCount; i++)
        vec.get(l - 1).add(i);
 
    // store nodes of rest of
    // the level by moving in
    // bottom-up manner
    for (int i = l - 2; i >= 0; i--)
    {
        int k = 0;
 
        // loop to calculate values
        // of parent nodes from the
        // children nodes of lower level
        while (k < vec.get(i + 1).size() - 1)
        {
 
            // store the value of parent
            // node as sum of children nodes
            vec.get(i).add(vec.get(i + 1).get(k) +
                           vec.get(i + 1).get(k + 1));
            k += 2;
        }
    }
 
    int sum = 0;
 
    // traverse the list of vector
    // and calculate the sum
    for (int i = 0; i < l; i++)
    {
        for (int j = 0;
                 j < vec.get(i).size(); j++)
            sum += vec.get(i).get(j);
    }
 
    return sum;
}
 
// Driver Code
public static void main(String args[])
{
    int l = 3;
 
    System.out.println(sumNodes(l));
}
}
 
// This code is contributed
// by Arnab Kundu


Python3
# Python3 program to implement the
# above approach
 
# function to find Sum of all of the
# nodes of given perfect binary tree
def SumNodes(l):
     
    # no of leaf nodes
    leafNodeCount = pow(2, l - 1)
 
    # list of vector to store nodes of
    # all of the levels
    vec = [[] for i in range(l)]
 
    # store the nodes of last level
    # i.e., the leaf nodes
    for i in range(1, leafNodeCount + 1):
        vec[l - 1].append(i)
 
    # store nodes of rest of the level
    # by moving in bottom-up manner
    for i in range(l - 2, -1, -1):
        k = 0
 
        # loop to calculate values of parent nodes
        # from the children nodes of lower level
        while (k < len(vec[i + 1]) - 1):
 
            # store the value of parent node as
            # Sum of children nodes
            vec[i].append(vec[i + 1][k] +
                          vec[i + 1][k + 1])
            k += 2
 
    Sum = 0
 
    # traverse the list of vector
    # and calculate the Sum
    for i in range(l):
        for j in range(len(vec[i])):
            Sum += vec[i][j]
 
    return Sum
 
# Driver Code
if __name__ == '__main__':
    l = 3
 
    print(SumNodes(l))
     
# This code is contributed by PranchalK


C#
using System;
using System.Collections.Generic;
 
// C# program to implement 
// the above approach
public class GFG
{
 
// function to find sum of 
// all of the nodes of given
// perfect binary tree 
public static int sumNodes(int l)
{
    // no of leaf nodes 
    int leafNodeCount = (int)Math.Pow(2, l - 1);
 
    // list of vector to store 
    // nodes of all of the levels 
    List> vec = new List>();
 
    //initialize
    for (int i = 1; i <= l; i++)
    {
    vec.Add(new List());
    }
 
    // store the nodes of last level 
    // i.e., the leaf nodes 
    for (int i = 1; i <= leafNodeCount; i++)
    {
        vec[l - 1].Add(i);
    }
 
    // store nodes of rest of 
    // the level by moving in 
    // bottom-up manner 
    for (int i = l - 2; i >= 0; i--)
    {
        int k = 0;
 
        // loop to calculate values 
        // of parent nodes from the
        // children nodes of lower level 
        while (k < vec[i + 1].Count - 1)
        {
 
            // store the value of parent
            // node as sum of children nodes 
            vec[i].Add(vec[i + 1][k] + vec[i + 1][k + 1]);
            k += 2;
        }
    }
 
    int sum = 0;
 
    // traverse the list of vector 
    // and calculate the sum 
    for (int i = 0; i < l; i++)
    {
        for (int j = 0; j < vec[i].Count; j++)
        {
            sum += vec[i][j];
        }
    }
 
    return sum;
}
 
// Driver Code 
public static void Main(string[] args)
{
    int l = 3;
 
    Console.WriteLine(sumNodes(l));
}
}
 
  // This code is contributed by Shrikant13


Javascript


C++
#include 
using namespace std;
 
// function to find sum of all of the nodes
// of given perfect binary tree
int sumNodes(int l)
{
    // no of leaf nodes
    int leafNodeCount = pow(2, l - 1);
 
    int sumLastLevel = 0;
 
    // sum of nodes at last level
    sumLastLevel = (leafNodeCount * (leafNodeCount + 1)) / 2;
 
    // sum of all nodes
    int sum = sumLastLevel * l;
 
    return sum;
}
 
// Driver Code
int main()
{
    int l = 3;
    cout << sumNodes(l);
    return 0;
}


Java
// Java code to find sum of all nodes
// of the given perfect binary tree
import java.io.*;
import java.lang.Math;
 
class GFG {
     
    // function to find sum of
    // all of the nodes of given
    // perfect binary tree
    static double sumNodes(int l)
    {
         
        // no of leaf nodes
        double leafNodeCount = Math.pow(2, l - 1);
     
        double sumLastLevel = 0;
     
        // sum of nodes at last level
        sumLastLevel = (leafNodeCount *
            (leafNodeCount + 1)) / 2;
     
        // sum of all nodes
        double sum = sumLastLevel * l;
     
        return sum;
    }
     
    // Driver Code
    public static void main (String[] args) {
     
        int l = 3;
        System.out.println(sumNodes(l));
    }
}
 
// This code is contributed by
// Anuj_{AJ_67}


Python3
# function to find sum of all of the nodes
# of given perfect binary tree
import math
 
def sumNodes(l):
     
    # no of leaf nodes
    leafNodeCount = math.pow(2, l - 1);
 
    sumLastLevel = 0;
 
    # sum of nodes at last level
    sumLastLevel = ((leafNodeCount *
                  (leafNodeCount + 1)) / 2);
 
    # sum of all nodes
    sum = sumLastLevel * l;
 
    return int(sum);
 
# Driver Code
l = 3;
print (sumNodes(l));
 
# This code is contributed by manishshaw


C#
// C# code to find sum of all nodes
// of the given perfect binary tree
using System;
using System.Collections.Generic;
 
class GFG {
     
    // function to find sum of
    // all of the nodes of given
    // perfect binary tree
    static double sumNodes(int l)
    {
         
        // no of leaf nodes
        double leafNodeCount = Math.Pow(2, l - 1);
     
        double sumLastLevel = 0;
     
        // sum of nodes at last level
        sumLastLevel = (leafNodeCount *
               (leafNodeCount + 1)) / 2;
     
        // sum of all nodes
        double sum = sumLastLevel * l;
     
        return sum;
    }
     
    // Driver Code
    public static void Main()
    {
        int l = 3;
        Console.Write(sumNodes(l));
    }
}
 
// This code is contributed by
// Manish Shaw (manishshaw1)


PHP


Javascript


输出:

30

时间复杂度:O(n),其中 n 是完美二叉树中的节点总数。
有效方法:一种有效的方法是观察我们只需要找到所有节点的总和。使用前n个自然数之和的公式,我们可以很容易地得到最后一层所有节点的总和。此外,可以看出,由于它是一棵完美的二叉树,父节点将是子节点的总和,因此所有级别的节点总和将相同。因此,我们只需要找到最后一层的节点总和,然后乘以总层数。
下面是上述想法的实现:

C++

#include 
using namespace std;
 
// function to find sum of all of the nodes
// of given perfect binary tree
int sumNodes(int l)
{
    // no of leaf nodes
    int leafNodeCount = pow(2, l - 1);
 
    int sumLastLevel = 0;
 
    // sum of nodes at last level
    sumLastLevel = (leafNodeCount * (leafNodeCount + 1)) / 2;
 
    // sum of all nodes
    int sum = sumLastLevel * l;
 
    return sum;
}
 
// Driver Code
int main()
{
    int l = 3;
    cout << sumNodes(l);
    return 0;
}

Java

// Java code to find sum of all nodes
// of the given perfect binary tree
import java.io.*;
import java.lang.Math;
 
class GFG {
     
    // function to find sum of
    // all of the nodes of given
    // perfect binary tree
    static double sumNodes(int l)
    {
         
        // no of leaf nodes
        double leafNodeCount = Math.pow(2, l - 1);
     
        double sumLastLevel = 0;
     
        // sum of nodes at last level
        sumLastLevel = (leafNodeCount *
            (leafNodeCount + 1)) / 2;
     
        // sum of all nodes
        double sum = sumLastLevel * l;
     
        return sum;
    }
     
    // Driver Code
    public static void main (String[] args) {
     
        int l = 3;
        System.out.println(sumNodes(l));
    }
}
 
// This code is contributed by
// Anuj_{AJ_67}

Python3

# function to find sum of all of the nodes
# of given perfect binary tree
import math
 
def sumNodes(l):
     
    # no of leaf nodes
    leafNodeCount = math.pow(2, l - 1);
 
    sumLastLevel = 0;
 
    # sum of nodes at last level
    sumLastLevel = ((leafNodeCount *
                  (leafNodeCount + 1)) / 2);
 
    # sum of all nodes
    sum = sumLastLevel * l;
 
    return int(sum);
 
# Driver Code
l = 3;
print (sumNodes(l));
 
# This code is contributed by manishshaw

C#

// C# code to find sum of all nodes
// of the given perfect binary tree
using System;
using System.Collections.Generic;
 
class GFG {
     
    // function to find sum of
    // all of the nodes of given
    // perfect binary tree
    static double sumNodes(int l)
    {
         
        // no of leaf nodes
        double leafNodeCount = Math.Pow(2, l - 1);
     
        double sumLastLevel = 0;
     
        // sum of nodes at last level
        sumLastLevel = (leafNodeCount *
               (leafNodeCount + 1)) / 2;
     
        // sum of all nodes
        double sum = sumLastLevel * l;
     
        return sum;
    }
     
    // Driver Code
    public static void Main()
    {
        int l = 3;
        Console.Write(sumNodes(l));
    }
}
 
// This code is contributed by
// Manish Shaw (manishshaw1)

PHP


Javascript


输出:

30

时间复杂度:O(1)