Producto de Nodes en el k-ésimo nivel en un árbol representado como string

Dado un entero ‘K’ y un árbol binario en formato de string. Cada Node de un árbol tiene un valor en el rango de 0 a 9. Necesitamos encontrar el producto de los elementos en el nivel K-ésimo desde la raíz. La raíz está en el nivel 0. 
Nota: el árbol se da en la forma: (valor del Node (subárbol izquierdo) (subárbol derecho)) 
Ejemplos: 
 

Input : tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))" 
        k = 2
Output : 72
Its tree representation is shown below

C++

// C++ implementation to find product of
// digits of elements at k-th level
#include <bits/stdc++.h>
using namespace std;
  
// Function to find product of digits
// of elements at k-th level
int productAtKthLevel(string tree, int k)
{
    int level = -1;
    int product = 1; // Initialize result
    int n = tree.length();
  
    for (int i = 0; i < n; i++) {
        // increasing level number
        if (tree[i] == '(')
            level++;
  
        // decreasing level number
        else if (tree[i] == ')')
            level--;
  
        else {
            // check if current level is
            // the desired level or not
            if (level == k)
                product *= (tree[i] - '0');
        }
    }
  
    // required product
    return product;
}
  
// Driver program
int main()
{
    string tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
    int k = 2;
    cout << productAtKthLevel(tree, k);
    return 0;
}

Java

// Java implementation to find product of
// digits of elements at k-th level
  
class GFG
{
    // Function to find product of digits
    // of elements at k-th level
    static int productAtKthLevel(String tree, int k)
    {
        int level = -1;
          
        // Initialize result
        int product = 1; 
          
        int n = tree.length();
      
        for (int i = 0; i < n; i++) 
        {
            // increasing level number
            if (tree.charAt(i) == '(')
                level++;
      
            // decreasing level number
            else if (tree.charAt(i) == ')')
                level--;
      
            else 
            {
                // check if current level is
                // the desired level or not
                if (level == k)
                    product *= (tree.charAt(i) - '0');
            }
        }
      
        // required product
        return product;
    }
      
    // Driver program
    public static void main(String[] args)
    {
        String tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
        int k = 2;
        System.out.println(productAtKthLevel(tree, k));
    }
}
  
// This code is contributed 
// by Smitha Dinesh Semwal.

Python3

# Python 3 implementation
# to find product of
# digits of elements
# at k-th level
  
# Function to find
# product of digits
# of elements at
# k-th level
def productAtKthLevel(tree, k):
  
    level = -1
          
        # Initialize result
    product = 1 
    n = len(tree)
  
    for i in range(0, n): 
  
        # increasing level number
        if (tree[i] == '('):
            level+=1
  
        # decreasing level number
        elif (tree[i] == ')'):
            level-=1
  
        else:
            # check if current level is
            # the desired level or not
            if (level == k):
                product *= (int(tree[i]) - int('0'))
          
      
  
    # required product
    return product
  
  
# Driver program
tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))"
k = 2
  
print(productAtKthLevel(tree, k))
  
# This code is contributed by
# Smitha Dinesh Semwal

C#

// C# implementation to find 
// product of digits of
// elements at k-th level
using System;
  
class GFG
{
    // Function to find product 
    // of digits of elements 
    // at k-th level
    static int productAtKthLevel(string tree,
                                 int k)
    {
        int level = -1;
          
        // Initialize result
        int product = 1; 
          
        int n = tree.Length;
      
        for (int i = 0; i < n; i++) 
        {
            // increasing 
            // level number
            if (tree[i] == '(')
                level++;
      
            // decreasing 
            // level number
            else if (tree[i] == ')')
                level--;
      
            else
            {
                // check if current level is
                // the desired level or not
                if (level == k)
                    product *= (tree[i] - '0');
            }
        }
      
        // required product
        return product;
    }
      
    // Driver Code
    static void Main()
    {
        string tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
        int k = 2;
        Console.WriteLine(productAtKthLevel(tree, k));
    }
}
  
// This code is contributed by Sam007 

PHP

<?php
// php implementation to find product of
// digits of elements at k-th level
  
// Function to find product of digits
// of elements at k-th level
function productAtKthLevel($tree, $k)
{
    $level = -1;
    $product = 1; // Initialize result
    $n = strlen($tree);
  
    for ($i = 0; $i < $n; $i++) 
    {
          
        // increasing level number
        if ($tree[$i] == '(')
            $level++;
  
        // decreasing level number
        else if ($tree[$i] == ')')
            $level--;
  
        else 
        {
            // check if current level is
            // the desired level or not
            if ($level == $k)
                $product *= (ord($tree[$i]) -
                             ord('0'));
        }
    }
  
    // required product
    return $product;
}
  
    // Driver Code
    $tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
    $k = 2;
    echo productAtKthLevel($tree, $k);
  
//This code is contributed by mits 
?>

Javascript

<script>
    // Javascript implementation to find 
    // product of digits of
    // elements at k-th level
      
    // Function to find product 
    // of digits of elements 
    // at k-th level
    function productAtKthLevel(tree, k)
    {
        let level = -1;
            
        // Initialize result
        let product = 1; 
            
        let n = tree.length;
        
        for (let i = 0; i < n; i++) 
        {
            // increasing 
            // level number
            if (tree[i] == '(')
                level++;
        
            // decreasing 
            // level number
            else if (tree[i] == ')')
                level--;
        
            else
            {
                // check if current level is
                // the desired level or not
                if (level == k)
                    product *= (tree[i].charCodeAt() - '0'.charCodeAt());
            }
        }
        
        // required product
        return product;
    }
      
    let tree = "(0(5(6()())(4()(9()())))(7(1()())(3()())))";
    let k = 2;
    document.write(productAtKthLevel(tree, k));
          
</script>

Publicación traducida automáticamente

Artículo escrito por Sahil_Bansall y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *