222. Count Complete Tree Nodes
Last updated
Last updated
/**
* 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) {
int h=height(root);
return h==-1?0:
height(root->right)==h-1?(1<<h)+countNodes(root->right):
(1<<(h-1))+countNodes(root->left);
}
int height(TreeNode* root){
return root==NULL?-1:height(root->left)+1; //由于保证是完全二叉树,所以计算高度直接在左边即可
}
};T(n) = T(n/2) + c1 lgn
= T(n/4) + c1 lgn + c2 (lgn - 1)
= ...
= T(1) + c [lgn + (lgn-1) + (lgn-2) + ... + 1]
= O(lgn*lgn)