码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode 222. Count Complete Tree Nodes

时间:2019-06-03 14:12:08      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:因此   nbsp   tree node   arch   满二叉树   log   arc   除了   ++   

由于是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

标签:因此   nbsp   tree node   arch   满二叉树   log   arc   除了   ++   

原文地址:https://www.cnblogs.com/hankunyan/p/10967147.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!