The thought is simple. We just consider the lowest level of the tree.

The left child and right child just divide the tree lower than the current node to 2 part.

So what this code do is first check the right most child of the current node's left child.

If this child is exist, we know that there may be more nodes on the right side of the tree. So we move the current node to it's right child. And repeat until we reach the lowest level.

```
int countNodes(TreeNode* root) {
if(!root) return 0;
TreeNode *temp = root;
int height = 0, count = 0, level;
while(temp) {
temp = temp->left;
height ++;
}
temp = root;
level = height - 2;
while(level >= 0) {
TreeNode *left = temp->left;
for(int i = 0;i < level;i ++) {
left = left->right;
}
if(left) {
temp = temp->right;
count += (1 << level);
} else temp = temp->left;
level --;
}
if(temp) count ++;
return (1 << (height - 1)) + count - 1;
}
```