이진 트리가 주어지면 이 함수는 노드에 저장된 키의 이진 값을 생성한 다음 해당 이진법에서 설정된 비트 수(1)를 반환합니다.

예시
다음과 같은 키를 갖는 이진 트리:10 3 211 140 162 100 및 146
| 키 | 동등한 바이너리 | 비트 설정(출력) |
|---|---|---|
| 10 | 1010 | 2 |
| 3 | 0011 | 2 |
| 211 | 11010011 | 5 |
| 140 | 10001100 | 3 |
| 162 | 10100010 | 3 |
| 100 | 1100100 | 3 |
| 146 | 10010010 | 3 |
여기서 __builtin_popcount 함수를 사용하고 있습니다.
함수 프로토타입은 다음과 같습니다 -
int __builtin_popcount(unsigned int)
정수로 설정된 비트 수, 즉 정수의 이진 표현에서 1의 수를 반환합니다.
알고리즘
START Step 1 -> create a structure of a node as struct Node struct node *left, *right int data End Step 2 -> function to create a node node* newnode(int data) node->data = data node->left = node->right = NULL; return (node) Step 3 -> Create function for generating bits of a node data void bits(Node* root) IF root = NULL return print __builtin_popcount(root->data) bits(root->left) bits(root->right) step 4 -> In main() create tree using Node* root = newnode(10) root->left = newnode(3) call bits(root) STOP
예시
#include <bits/stdc++.h>
using namespace std;
// structure of a node
struct Node {
int data;
struct Node *left, *right;
};
//function to create a new node
Node* newnode(int data) {
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
//function for finding out the node
void bits(Node* root){
if (root == NULL)
return;
//__builtin_popcount counts the number of set bit of a current node
cout << "bits in node " << root->data << " = " <<__builtin_popcount(root->data)<< "\n";
bits(root->left);
bits(root->right);
}
int main(){
Node* root = newnode(10);
root->left = newnode(3);
root->left->left = newnode(140);
root->left->right = newnode(162);
root->right = newnode(211);
root->right->left = newnode(100);
root->right->right = newnode(146);
bits(root);
return 0;
} 출력
위의 프로그램을 실행하면 다음 출력이 생성됩니다.
bits in node 10 = 2 bits in node 3 = 2 bits in node 140 = 3 bits in node 162 = 3 bits in node 211 = 5 bits in node 100 = 3 bits in node 146 = 3