/** * 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) return 0;
        int l_num = getDepth(root->left);
        int r_num = getDepth(root->right);
        if(l_num==r_num)
            return pow(2,l_num) + countNodes(root->right);
        else
            return pow(2,r_num) + countNodes(root->left);
    }
    
    int getDepth(TreeNode* root) {
        if(!root) return 0;
        int res = 1;
        while(root->left) {
            root = root->left;
            ++res;
        }
        return res;
    }
};

解析

完全二叉树的结点的个数

暴力解:遍历一遍二叉树随便什么遍历方式O(N) 的时间复杂度
利用完全二叉树的特性加速;完全二叉树和满二叉树只有一点的区别,在完全二叉树的最后一层是不满的其余的都是满的。所以只需要知道根节点的左右子树的高度是否一致就可以判断那一块是满二叉树

  1. 如果左右子树最左的高度相等那么根节点的左子树必然是满二叉树,利用2^n -1直接计算出左子树的结点个数。
  2. 如果左右子树延左边界的高度不相等只有可能是左边的高度大于右边那么右子树必然是满二叉树。同理去计算。

这样的好处是只需要o(logn)的时间复杂度就可以排除一半的结点数量,不需要一一计算。每一层只计算一个结点,每个结点得到其左右子树的左边界的高度o(logn)这样整体的复杂度为O(logn)^2得到很大的加速。