📌  相关文章
📜  求同级叶子数据总和的乘积 | 2套

📅  最后修改于: 2021-10-27 09:08:46             🧑  作者: Mango

给定一个二叉树,为其返回以下值。

  • 对于每一层,如果该层有叶子,则计算所有叶子的总和。否则忽略它。
  • 返回所有和的乘法。

例子

Input: Root of below tree
         2
       /   \
      7     5
             \
              9
Output: 63
First levels doesn't have leaves. Second level
has one leaf 7 and third level also has one 
leaf 9. Therefore result is 7*9 = 63

Input: Root of below tree
         2
       /   \
     7      5
    / \      \
   8   6      9
      / \    /  \
     1  11  4    10 

Output: 208
First two levels don't have leaves. Third
level has single leaf 8. Last level has four
leaves 1, 11, 4 and 10. Therefore result is 
8 * (1 + 11 + 4 + 10)  

在上一篇文章中,我们已经看到了使用级别顺序遍历的基于队列的解决方案。
在这里,我们只是简单地对二叉树进行前序遍历,我们在 C++ STL 中使用了 unordered_map 来存储相同级别的叶子节点的总和。然后在地图的单次遍历中,我们计算了级别总和的最终乘积。
下面是上述方法的实现:

C++
// C++ program to find product of sums
// of data of leaves at same levels
// using map in STL
#include 
using namespace std;
 
// Binary Tree Node
struct Node {
    int data;
    Node* left;
    Node* right;
};
 
// Utility function to create
// a new Tree node
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// Helper function to calculate sum of
// leaf nodes at same level and store in
// an unordered_map
void productOfLevelSumUtil(Node* root,
       unordered_map& level_sum,
                                int level)
{
 
    if (!root)
        return;
 
    // Check if current node is a leaf node
    // If yes add it to sum of current level
    if (!root->left && !root->right)
        level_sum[level] += root->data;
 
    // Traverse left subtree
    productOfLevelSumUtil(root->left, level_sum,
                          level + 1);
 
    // Traverse right subtree
    productOfLevelSumUtil(root->right, level_sum,
                          level + 1);
}
 
// Function to calculate product of level sums
int productOfLevelSum(Node* root)
{
    // Create a map to store sum of leaf
    // nodes at same levels.
    unordered_map level_sum;
 
    // Call the helper function to
    // calculate level sums of leaf nodes
    productOfLevelSumUtil(root, level_sum, 0);
 
    // variable to store final product
    int prod = 1;
 
    // Traverse the map to calculate product
    // of level sums
    for (auto it = level_sum.begin();
                it != level_sum.end(); it++)
        prod *= it->second;
 
    // Return the result
    return prod;
}
 
// Driver Code
int main()
{
    // Creating Binary Tree
    Node* root = newNode(2);
    root->left = newNode(7);
    root->right = newNode(5);
    root->left->right = newNode(6);
    root->left->left = newNode(8);
    root->left->right->left = newNode(1);
    root->left->right->right = newNode(11);
    root->right->right = newNode(9);
    root->right->right->left = newNode(4);
    root->right->right->right = newNode(10);
 
    cout << "Final product is = "
         << productOfLevelSum(root) << endl;
 
    return 0;
}


Java
// Java program to find product of sums
// of data of leaves at same levels
// using map in STL
import java.util.*;
public class GFG
{
    // Binary Tree Node
    static class Node {
        
        int data;
        Node left, right;
        
        Node(int item)
        {
            data = item;
            left = right = null;
        }
    }
     
    // Root of the Binary Tree
    Node root;
    public GFG()
    {
        root = null;
    }
     
    // Utility function to create
    // a new Tree node
    static Node newNode(int data)
    {
        Node temp = new Node(data);
        return (temp);
    }
   
    // Create a map to store sum of leaf
    // nodes at same levels.
    static HashMap level_sum = new HashMap<>();
   
    // Helper function to calculate sum of
    // leaf nodes at same level and store in
    // an unordered_map
    static void productOfLevelSumUtil(Node root, int level)
    {
   
        if (root == null)
            return;
   
        // Check if current node is a leaf node
        // If yes add it to sum of current level
        if (root.left == null && root.right == null)
        {
            if(level_sum.containsKey(level))
            { 
                level_sum.put(level, level_sum.get(level) + root.data);
            }
            else{
                level_sum.put(level, root.data);
            }
        }
   
        // Traverse left subtree
        productOfLevelSumUtil(root.left, level + 1);
   
        // Traverse right subtree
        productOfLevelSumUtil(root.right, level + 1);
    }
   
    // Function to calculate product of level sums
    static int productOfLevelSum(Node root)
    {
        // Call the helper function to
        // calculate level sums of leaf nodes
        productOfLevelSumUtil(root, 0);
   
        // variable to store final product
        int prod = 1;
   
        // Traverse the map to calculate product
        // of level sums
        for (Map.Entry it : level_sum.entrySet())
        {
            prod *= it.getValue();
        }
   
        // Return the result
        return prod;
    }
     
    public static void main(String[] args) {
        // Creating Binary Tree
        GFG tree = new GFG();
        tree.root = newNode(2);
        tree.root.left = newNode(7);
        tree.root.right = newNode(5);
        tree.root.left.right = newNode(6);
        tree.root.left.left = newNode(8);
        tree.root.left.right.left = newNode(1);
        tree.root.left.right.right = newNode(11);
        tree.root.right.right = newNode(9);
        tree.root.right.right.left = newNode(4);
        tree.root.right.right.right = newNode(10);
         
        System.out.print("Final product is = " + productOfLevelSum(tree.root));
    }
}
 
// This code is contributed by divyeshrabadiya07.


C#
// C# program to find product of sums
// of data of leaves at same levels
// using map in STL
using System;
using System.Collections;
using System.Collections.Generic;
 
// Binary Tree Node
class Node {
       
    public int data;
    public Node left, right;
   
    public Node(int item)
    {
        data = item;
        left = right = null;
    }
}
     
public class GFG {
     
    // Root of the Binary Tree
    Node root;
    public GFG()
    {
        root = null;
    }
    
    // Utility function to create
    // a new Tree node
    static Node newNode(int data)
    {
        Node temp = new Node(data);
        return (temp);
    }
  
    // Create a map to store sum of leaf
    // nodes at same levels.
    static Dictionary level_sum = new Dictionary();
  
    // Helper function to calculate sum of
    // leaf nodes at same level and store in
    // an unordered_map
    static void productOfLevelSumUtil(Node root, int level)
    {
  
        if (root == null)
            return;
  
        // Check if current node is a leaf node
        // If yes add it to sum of current level
        if (root.left == null && root.right == null)
        {
            if(level_sum.ContainsKey(level))
            {  
                level_sum[level] += root.data;
            }
            else{
                level_sum[level] = root.data;
            }
        }
  
        // Traverse left subtree
        productOfLevelSumUtil(root.left, level + 1);
  
        // Traverse right subtree
        productOfLevelSumUtil(root.right, level + 1);
    }
  
    // Function to calculate product of level sums
    static int productOfLevelSum(Node root)
    {
        // Call the helper function to
        // calculate level sums of leaf nodes
        productOfLevelSumUtil(root, 0);
  
        // variable to store final product
        int prod = 1;
  
        // Traverse the map to calculate product
        // of level sums
        foreach(KeyValuePair it in level_sum)
        {
            prod *= it.Value;
        }
  
        // Return the result
        return prod;
    }
 
  static void Main() {
       
    // Creating Binary Tree
    GFG tree = new GFG();
    tree.root = newNode(2);
    tree.root.left = newNode(7);
    tree.root.right = newNode(5);
    tree.root.left.right = newNode(6);
    tree.root.left.left = newNode(8);
    tree.root.left.right.left = newNode(1);
    tree.root.left.right.right = newNode(11);
    tree.root.right.right = newNode(9);
    tree.root.right.right.left = newNode(4);
    tree.root.right.right.right = newNode(10);
    
    Console.Write("Final product is = " + productOfLevelSum(tree.root));
  }
}
 
// This code is contributed by decode2207.


Javascript


输出:

Final product is = 208

时间复杂度:O(N)
辅助空间:O(N)
其中 N 是二叉树中的节点数。

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程