C++中计算二叉树中其值模2的高度小于2的节点数可以通过递归的方式实现。具体步骤如下:
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
int countNodes(TreeNode* root) {
if (root == nullptr) {
return 0;
}
int count = 0;
if (root->val % 2 < 2) {
count++;
}
count += countNodes(root->left);
count += countNodes(root->right);
return count;
}
int main() {
// 创建二叉树
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
root->right = new TreeNode(3);
root->left->left = new TreeNode(4);
root->left->right = new TreeNode(5);
root->right->left = new TreeNode(6);
root->right->right = new TreeNode(7);
// 计算满足条件的节点数
int result = countNodes(root);
cout << "满足条件的节点数:" << result << endl;
// 释放内存
delete root->left->left;
delete root->left->right;
delete root->right->left;
delete root->right->right;
delete root->left;
delete root->right;
delete root;
return 0;
}
以上代码实现了计算二叉树中其值模2的高度小于2的节点数。在这个例子中,二叉树的节点值都是整数,我们通过对节点值取模2来判断是否满足条件。具体的应用场景和推荐的腾讯云相关产品和产品介绍链接地址需要根据实际需求来确定,可以参考腾讯云的官方文档和产品介绍页面获取更多信息。
领取专属 10元无门槛券
手把手带您无忧上云