题意:求完全二叉树的节点个数。
分析:
暴力枚举O(n)会超时。
首先,我们知道满二叉树的节点个数为2^h-1,其中h为树的高度;
其次,将完全二叉树都划分为左子树、根、右子树,由完全二叉树的定义可知,左右子树至少有一棵是满二叉树,于是总节点个数 countNodes(root) = 1+countNodes(root->left)+countNodes(root->right);
最后,还有一个问题,就是如何判断左、右子树是否为满二叉树,常规想法就是分别计算左、右子树的深度,如果深度相同,则左子树为满二叉树,如果深度不同(左子树比右子树大1),则右子树为满二叉树。复杂度仍为O(n)。其实不用这么麻烦,根据完全二叉树和满二叉树的定义,只需最左子树和最右子树的深度相同,则为满二叉树。复杂度为O(h^2)。
代码:
/**
* 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;
int lh=0;
int rh=0;
TreeNode *left=root;
TreeNode *right=root;
while(left){
lh++;
left=left->left;
}
while(right){
rh++;
right=right->right;
}
if(lh==rh) return pow(2,lh)-1;
return 1+countNodes(root->left)+countNodes(root->right);
}
};