2023.7.3
用层序遍历遍历一遍二叉树,然后遍历的每个节点都进行一次计数,直接上代码:
class Solution {
public:
int countNodes(TreeNode* root) {
queue<TreeNode*> que;
int ans = 0;
if(root == nullptr) return ans;
que.push(root);
while(!que.empty())
{
int size = que.size();
while(size--)
{
TreeNode* node = que.front();
que.pop();
ans++;
if(node->left) que.push(node->left);
if(node->right) que.push(node->right);
}
}
return ans;
}
};