- 二叉树通用递归
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0 ;
return countNodes(root->left) + countNodes(root->right) + 1;
}
};
- 结合满二叉树的特点在普通递归基础上进行剪枝
从根节点出发,一路向左遍历的的深度等于一路向右的深度,那么左右子树一定是满二叉树直接通过公式进行计算,否则还是按照正常的递归进行
pow(2,hleft+1) -1; == 2 << hleft - 1 前者需要调用函数,后者位运算稍微快一点
class Solution {
public:
int countNodes(TreeNode* root) {
if(!root) return 0;
TreeNode* left = root->left;
TreeNode* right = root->right;
int hleft = 0;
int hright = 0;
while(left){
left = left->left;
hleft++;
}
while(right){
right = right->right;
hright++;
}
if(hleft == hright) return pow(2,hleft+1) -1;
return countNodes(root->left) + countNodes(root->right) + 1;
}
};