C++ | Leetcode C++题解之第22题完全二叉树的节点个数

题目:

题解:

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;
    }
};

相关推荐

  1. 222. 完全节点个数

    2024-07-09 21:00:06       56 阅读
  2. LeetCode 222.完全节点个数

    2024-07-09 21:00:06       46 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-09 21:00:06       99 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-09 21:00:06       107 阅读
  3. 在Django里面运行非项目文件

    2024-07-09 21:00:06       90 阅读
  4. Python语言-面向对象

    2024-07-09 21:00:06       98 阅读

热门阅读

  1. 设计模式的一点理解

    2024-07-09 21:00:06       22 阅读
  2. QT 设置控件的展开和消失

    2024-07-09 21:00:06       25 阅读
  3. qt 读取配置文件

    2024-07-09 21:00:06       25 阅读
  4. 王道考研数据机构:中缀表达式转为后缀表达式

    2024-07-09 21:00:06       35 阅读
  5. 基于深度学习的夜间图像修复

    2024-07-09 21:00:06       29 阅读
  6. SQL AND & OR 运算符的使用与区别

    2024-07-09 21:00:06       26 阅读
  7. VSCode中常用的快捷键

    2024-07-09 21:00:06       24 阅读