计算C ++中XOR为奇数的所有相邻节点对
在本教程中,我们将讨论一个程序,以查找XOR为奇数的相邻节点对的数量。
为此,我们将提供一个二叉树。我们的任务是计算XOR为奇数的相邻元素对的数量。
示例
#include <iostream>
using namespace std;
//树的节点结构
struct Node {
int data;
struct Node *left, *right;
};
//查找其异或
//很奇怪
int count_pair(Node* root, Node *parent=NULL){
if (root == NULL)
return 0;
//checking pair of XOR 很奇怪 or not
int res = 0;
if (parent != NULL && (parent->data ^ root->data) % 2)
res++;
return res + count_pair(root->left, root) + count_pair(root->right, root);
}
//创建新节点
Node* newNode(int data){
Node* temp = new Node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
int main(){
struct Node* root = NULL;
root = newNode(15);
root->left = newNode(13);
root->left->left = newNode(12);
root->left->right = newNode(14);
root->right = newNode(18);
root->right->left = newNode(17);
root->right->right = newNode(21);
printf("%d ", count_pair(root));
return 0;
}输出结果
5
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿