LeetCode 222. Count Complete Tree Nodes

Posted hankunyan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;
    
;

 

以上是关于LeetCode 222. Count Complete Tree Nodes的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode222——Count Complete Tree Nodes

Leetcode 222. Count Complete Tree Nodes

LeetCode OJ 222. Count Complete Tree Nodes

[LeetCode] 222. Count Complete Tree Nodes Java

[Leetcode] Binary search -- 222. Count Complete Tree Nodes

leetcode 222.Count Complete Tree Nodes