题目链接:222. 完全二叉树的节点个数 - 力扣(Leetcode)
class Solution {
public:
int countNodes(TreeNode* root) {
//完全二叉树有两种情况,一满二叉树则左子树与右子树深度相等,二非满二叉树则左子树和右子树深度不相等
if (root == nullptr) return 0;
TreeNode* leftNode = root->left;
TreeNode* rightNode = root->right;
int leftDepth = 1, rightDepth = 1;
while (leftNode) { // 求左子树深度
leftNode = leftNode->left;
leftDepth++;
}
while (rightNode) { // 求右子树深度
rightNode = rightNode->right;
rightDepth++;
}
if (leftDepth == rightDepth) {//如果左子树深度与右子树相等,则为满二叉树,直接求满二叉树的节点个数
return pow(2,leftDepth) - 1;
}
//如果左子树深度与右子树不相等,则为非满二叉树,递归找到最小的非满二叉树
return countNodes(root->left) + countNodes(root->right) + 1;
}
};