使用 C++ 程式設計列印二叉樹中每個結點的置位位數。
對於給定的二叉樹,該函式將生成儲存在結點中的鍵的二進位制值,然後返回該二進位制等價中置位位(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
広告