LeetCode 222. Count Complete Tree Nodes

由于是CBT,这道题一定是要用到CBT的性质,来减少时间复杂度。

由于是树的题,很容易想到递归,将原问题划归到子树上。完全二叉树除了最后一层一定是满的,因此子树中一定有一棵是满二叉树,而满二叉树的节点个数是2^n-1,接着只要计算另一棵的节点数即可。

在完全二叉树中,计算树的高度只要一路向左查看即可,O(logn)

T(n) = T(n/2) + O(logn)  =>  T(n) = O((logn)^2)

本题算不上divide and conquer,更像二分,tag 标的也是 Binary Search。

class Solution {
public:
    int countNodes(TreeNode* root) {
        if (root==NULL) return 0;
        int lh=height(root->left);
        int rh=height(root->right);
        if (lh==rh){
            return pow(2,lh) + countNodes(root->right);
        }
        return pow(2,rh) + countNodes(root->left);
    }
    
    int height(TreeNode *root){ //return the height of CBT, log(n)
        int count=0;
        while (root){
            ++count;
            root = root->left;
        }
        return count;
    }
};

 

posted @ 2019-06-03 13:51  約束の空  阅读(116)  评论(0)    收藏  举报