222. 完全二叉树的节点个数 - 力扣(LeetCode)
层次遍历:
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
queue<TreeNode*> q;
q.push(root);
int res = 0, cnt = 1;
while(!q.empty()){
int size = q.size();
if(size == cnt) res += cnt;
else{
res += size; break;
}
cnt *= 2;
for(int i = 0; i < size; ++i){
auto cur = q.front();
q.pop();
if(cur->left) q.push(cur->left);
if(cur->right) q.push(cur->right);
}
}
return res;
}
};
递归:
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
return countNodes(root->left) + countNodes(root->right) + 1;
}
};