文章
7
粉丝
0
获赞
0
访问
3.6k
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 辅助函数:获取子树中的最大值(左子树用)
int getMax(TreeNode *root) {
if (root == NULL) return INT_MIN;
while (root->right != NULL) {
root = root->right;
}
return root->val;
}
// 辅助函数:获取子树中的最小值(右子树用)
int getMin(TreeNode *root) {
if (root == NULL) return INT_MAX;
while (root->left != NULL) {
root = root->left;
}
return root->val;
}
int countNodes(TreeNode* root) {
if (root == NULL) return 0;
int cnt = 0;
// 递归统计左、右子树的符合条件节点数
cnt += countNodes(root->left);
cnt += countNodes(root->right);
// 判断当前节点是否同时有左、右子树
if (root->left != NULL && root->right != NULL) {
int leftMax = getMax(root->left); // 左子树最大值
int rightMin = getMin(root->right); // 右子树最小值
...
登录后发布评论
暂无评论,来抢沙发