https://leetcode.com/problems/count-complete-tree-nodes/
层次遍历二叉树,将节点压入队列,取出队列头部,将其左右子树压入队列。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int countNodes(TreeNode* root) {
if(root==nullptr)
return 0;
if(root->left==nullptr && root->right==nullptr)
return 1;
queue<TreeNode*> q;
q.push(root);
int n = 0;
while(!q.empty()){
n+=1;
TreeNode* tmp = q.front();
q.pop();
if(tmp->left!=nullptr)
q.push(tmp->left);
if(tmp->right!=nullptr)
q.push(tmp->right);
}
return n;
}
};