LeetCode/完全二叉树的节点个数

1. 深度优先

class Solution {
public:
    int countNodes(TreeNode* root) {
        if(!root) return 0;
        return 1+countNodes(root->left)+countNodes(root->right);
    }
};

2. 广度优先

class Solution {
public:
    int countNodes(TreeNode* root) {
        if(!root) return 0;
        int count = 0;
        auto q = queue<TreeNode*>();
        q.push(root);
        while (!q.empty()) {
            for (int i = 0; i < q.size(); i++) {
                auto node = q.front();
                q.pop();
                if (node->left) q.push(node->left);
                if (node->right) q.push(node->right);
                count++;
            }
        }
        return count;
    }
}

3. 深度优先简化计算

通过判断子树是否是完全二叉树,直接计算

class Solution {
public:
    int countNodes(TreeNode* root) {
        if(!root) return 0;
        int left = countLevel(root->left);
        int right = countLevel(root->right);
        if(left == right)
            return countNodes(root->right) + (1<<left);
        else return countNodes(root->left) + (1<<right);
    }
    int countLevel(TreeNode* root){
        int level = 0;
        while(root){
            level++;
            root = root ->left;
        }
        return level;
    }
};

4. 二分查找+位运算(看不懂)

点击查看代码
class Solution {
public:
    int countNodes(TreeNode* root) {
        if (root == nullptr) {
            return 0;
        }
        int level = 0;
        TreeNode* node = root;
        while (node->left != nullptr) {
            level++;
            node = node->left;
        }
        int low = 1 << level, high = (1 << (level + 1)) - 1;
        while (low < high) {
            int mid = (high - low + 1) / 2 + low;
            if (exists(root, level, mid)) {
                low = mid;
            } else {
                high = mid - 1;
            }
        }
        return low;
    }

    bool exists(TreeNode* root, int level, int k) {
        int bits = 1 << (level - 1);
        TreeNode* node = root;
        while (node != nullptr && bits > 0) {
            if (!(bits & k)) {
                node = node->left;
            } else {
                node = node->right;
            }
            bits >>= 1;
        }
        return node != nullptr;
    }
};
posted @ 2022-07-25 23:15  失控D大白兔  阅读(14)  评论(0编辑  收藏  举报