Imprime el número de bits establecidos en cada Node de un árbol binario

Dado un árbol binario. La tarea es imprimir el número de bits establecidos en cada uno de los Nodes del árbol binario.
 

La idea es atravesar el árbol binario dado utilizando cualquier método de recorrido de árbol , y para cada Node calcular el número de bits establecidos e imprimirlo. 

Nota : También se puede usar la función __builtin_popcount() disponible en C++ para contar directamente el número de bits establecidos en un número entero.

A continuación se muestra la implementación del enfoque anterior: 

C++

// CPP program to print the number of set bits
// in each node of the binary tree
 
#include <bits/stdc++.h>
 
using namespace std;
 
// Binary Tree node
struct Node {
    int data;
    struct Node *left, *right;
};
 
// Utility function that allocates a new Node
Node* newNode(int data)
{
    Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
 
// Function to print the number of set bits
// in each node of the binary tree
void printSetBit(Node* root)
{
    if (root == NULL)
        return;
 
    // Print the number of set bits of
    // current node using __builtin_popcount()
    cout << "Set bits in Node " << root->data << " = " <<
                  __builtin_popcount(root->data) << "\n";
 
    // Traverse Left Subtree
    printSetBit(root->left);
 
    // Traverse Right Subtree
    printSetBit(root->right);
}
 
// Driver code
int main()
{
    Node* root = newNode(16);
    root->left = newNode(13);
    root->left->left = newNode(14);
    root->left->right = newNode(12);
    root->right = newNode(11);
    root->right->left = newNode(10);
    root->right->right = newNode(16);
 
    printSetBit(root);
 
    return 0;
}

Java

// Java program to print the number of set bits
// in each node of the binary tree
import java.util.*;
 
class GFG
{
 
// Binary Tree node
static class Node
{
    int data;
    Node left, right;
};
 
// Utility function that allocates a new Node
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return (node);
}
 
// Function to print the number of set bits
// in each node of the binary tree
static void printSetBit(Node root)
{
    if (root == null)
        return;
 
    // Print the number of set bits of
    // current node using __builtin_popcount()
    System.out.print("Set bits in Node " + root.data + " = " +
                      Integer.bitCount(root.data) + "\n");
 
    // Traverse Left Subtree
    printSetBit(root.left);
 
    // Traverse Right Subtree
    printSetBit(root.right);
}
 
// Driver code
public static void main(String[] args)
{
    Node root = newNode(16);
    root.left = newNode(13);
    root.left.left = newNode(14);
    root.left.right = newNode(12);
    root.right = newNode(11);
    root.right.left = newNode(10);
    root.right.right = newNode(16);
 
    printSetBit(root);
}
}
 
// This code is contributed by PrinciRaj1992

Python3

# Python3 program to print the number of set bits
# in each node of the binary tree
 
# Binary Tree node
class Node:
    def __init__(self):
        self.data = None
        self.left = None
        self.right = None
 
# Utility function that allocates a new Node
def newNode(data):
    node = Node()
    node.data = data
    node.left = None
    node.right = None
    return node
 
# Function to print the number of set bits
# in each node of the binary tree
def printSetBit(root: Node):
    if root is None:
        return
 
    # Print the number of set bits of
    # current node using count()
    print("Set bits in Node %d = %d" %
         (root.data, bin(root.data).count('1')))
 
    # Traverse Left Subtree
    printSetBit(root.left)
 
    # Traverse Right Subtree
    printSetBit(root.right)
 
# Driver Code
if __name__ == "__main__":
    root = newNode(16)
    root.left = newNode(13)
    root.left.left = newNode(14)
    root.left.right = newNode(12)
    root.right = newNode(11)
    root.right.left = newNode(10)
    root.right.right = newNode(16)
 
    printSetBit(root)
 
# This code is contributed by
# sanjeev2552

C#

// C# program to print the number of set bits
// in each node of the binary tree
using System;
     
class GFG
{
 
// Binary Tree node
public class Node
{
    public int data;
    public Node left, right;
};
 
// Utility function that allocates a new Node
static Node newNode(int data)
{
    Node node = new Node();
    node.data = data;
    node.left = node.right = null;
    return (node);
}
 
// Function to print the number of set bits
// in each node of the binary tree
static void printSetBit(Node root)
{
    if (root == null)
        return;
 
    // Print the number of set bits of
    // current node using __builtin_popcount()
    Console.Write("Set bits in Node " + root.data +
                  " = " + bitCount(root.data) + "\n");
 
    // Traverse Left Subtree
    printSetBit(root.left);
 
    // Traverse Right Subtree
    printSetBit(root.right);
}
 
static int bitCount(int x)
{
    int setBits = 0;
    while (x != 0)
    {
        x = x & (x - 1);
        setBits++;
    }
    return setBits;
}
 
// Driver code
public static void Main(String[] args)
{
    Node root = newNode(16);
    root.left = newNode(13);
    root.left.left = newNode(14);
    root.left.right = newNode(12);
    root.right = newNode(11);
    root.right.left = newNode(10);
    root.right.right = newNode(16);
 
    printSetBit(root);
}
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
 
// Javascript program to print the number
// of set bits in each node of the binary tree
 
// A Binary Tree Node
class Node
{
    constructor(data)
    {
        this.left = null;
        this.right = null;
        this.data = data;
    }
}
 
// Utility function that allocates a new Node
function newNode(data)
{
    let node = new Node(data);
    return (node);
}
 
function bitCount(x)
{
    let setBits = 0;
    while (x != 0)
    {
        x = x & (x - 1);
        setBits++;
    }
    return setBits;
}
 
// Function to print the number of set bits
// in each node of the binary tree
function printSetBit(root)
{
    if (root == null)
        return;
 
    // Print the number of set bits of
    // current node using __builtin_popcount()
    document.write("Set bits in Node " + root.data +
                   " = " + bitCount(root.data) + "</br>");
 
    // Traverse Left Subtree
    printSetBit(root.left);
 
    // Traverse Right Subtree
    printSetBit(root.right);
}
 
// Driver code
let root = newNode(16);
root.left = newNode(13);
root.left.left = newNode(14);
root.left.right = newNode(12);
root.right = newNode(11);
root.right.left = newNode(10);
root.right.right = newNode(16);
 
printSetBit(root);
 
// This code is contributed by suresh07
 
</script>
Producción: 

Set bits in Node 16 = 1
Set bits in Node 13 = 3
Set bits in Node 14 = 3
Set bits in Node 12 = 2
Set bits in Node 11 = 3
Set bits in Node 10 = 2
Set bits in Node 16 = 1

 

Publicación traducida automáticamente

Artículo escrito por Mohd_Saliem 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 *