class Solution {
public:
int countNodes(TreeNode* root) {
int res = 0;
while (root) {
int lh = 0, rh = 0;
for (TreeNode* p = root>left; p; p = p>left) ++lh;
for (TreeNode* p = root>right; p; p = p>left) ++rh;
res += (lh == rh)?(1 << lh):(1 << rh);
root = (lh == rh)?root>right:root = root>left;
}
return res;
}
};
My AC C++ solution


good code! Here is the formatted one.
class Solution { public: int countNodes(TreeNode* root) { int res = 0; while (root) { int lh = 0, rh = 0; for (TreeNode* p = root>left; p; p = p>left) ++lh; for (TreeNode* p = root>right; p; p = p>left) ++rh; res += (lh == rh)?(1 << lh):(1 << rh); root = (lh == rh)?root>right:root = root>left; } return res; } };