点击打开链接
class Solution {
public:
int countNodes(TreeNode* root) {
int hLeft=0, hRight=0;
TreeNode *pLeft = root, *pRight = root;
while (pLeft) {
hLeft+=1;
pLeft = pLeft->left;
}
while (pRight) {
hRight+=1;
pRight = pRight->right;
}
if(hLeft==hRight) return pow(2,hRight)-1;
return countNodes(root->left)+countNodes(root->right)+1; //必须用root
}
};
class Solution {
public:
queue<TreeNode*> Q;
int BFS(TreeNode* root)
{
if(root==NULL) return 0;
TreeNode *temple1=NULL;
int result =0;
Q.push(root); result+=1;
while (!Q.empty()) {
temple1 =Q.front(); Q.pop();
if(temple1->left){
Q.push(temple1->left);
result+=1;
}
if(temple1->right){
Q.push(temple1->right);
result+=1;
}
}
return result;
}
int countNodes(TreeNode* root) {
return BFS(root);
}