# C++ Solution inspired by couple of good ones.

• Concise C++ code I came up with after some inspiration from other solutions.

Thanks to:

1. 80ms C++ solution

class Solution {
public:
int countNodes(TreeNode* root) {
if (!root)
return 0;
int leftDepth = 0, rightDepth= 0;
for(TreeNode* p=root; p; p=p->left) ++leftDepth;
for(TreeNode* p=root; p; p=p->right) ++rightDepth;
if (leftDepth==rightDepth) {
return (1<< leftDepth) - 1 ;
}
else {
return countNodes(root->left) + countNodes(root->right) + 1 ;
}
}

};

• this answer is right, forgive me!

one bug
int leftDepth = 0, rightDepth= 0;
should be
int leftDepth = 1, rightDepth= 1;

• This post is deleted!

• original code is correct

• sorry about that, It was careless of me, your answer is similar to mine but a little difference.
i call it as the length of the path to the left child or right child. so i init it like this " int toleft=1,toright=1;".

• yes, he is right, it's my mistake.

• Easy to understand, good job. My iterative solution is not easy to understand.

• code simple,easy to get

• cool solution ! easy to understand. but I have a tiny question about cpp.
In this for loop:

for(TreeNode* p=root; p; p=p->left) ++leftDepth;

1. what do you mean of "p", does it mean p != 0 ?
2. when the for loop will end? when p does not have a left node?

• by the way, in this for loop:

for(TreeNode* p=root; p; p=p->left) ++leftDepth;

can I write "leftDepth++" ? Is there any difference here?

• This post is deleted!

• 1."p" means p != nullptr
2.the loop will end when the p is nullptr.

• ++leftDepth equals leftDepth = leftDepth + 1;
leftDepth++ equals {int left tmp = leftDepth; leftDepth = leftDepth + 1; return tmp}, that means leftDepth will make a copy of itself, it plus 1, and then return the copy.

• what's the time complexity of this solution?

• What's the time complexity?

• It's unnecessary to use prefix ++ in this case. The compiler will most definitely optimize it out and your code is less clear.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.