二分法求解。
/**
* 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;
TreeNode *t = root, *prev_tree = root;
int total = 0;
int h = -1;
while(t != nullptr) {
t = t->left;
h++;
}
total = (0x1 << h) - 1;
t = root;
int ch = 0;
int leftnode = 0;
while(ch < h){
prev_tree = t;
t = t->right; ch++;
for(int i = 0; i < h - ch; i++) t = t->left;
if(t == nullptr){
t = prev_tree->left;
} else {
t = prev_tree->right;
leftnode = leftnode + (0x1 << h - ch);
}
}
return total + leftnode + ((t == nullptr) ? 0 : 1);
}
};
当然,最暴力的递归方法也可以通过:
int find(TreeNode *root){
if(!t) return 0;
return 1 + find(t->left) + find(t->right);
}