Java | Leetcode Java题解之第222题完全二叉树的节点个数

题目:

题解:

java 复制代码
class Solution {
    public int countNodes(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int level = 0;
        TreeNode node = root;
        while (node.left != null) {
            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;
    }

    public boolean exists(TreeNode root, int level, int k) {
        int bits = 1 << (level - 1);
        TreeNode node = root;
        while (node != null && bits > 0) {
            if ((bits & k) == 0) {
                node = node.left;
            } else {
                node = node.right;
            }
            bits >>= 1;
        }
        return node != null;
    }
}
相关推荐
不知几秋3 分钟前
Spring Boot
java·前端·spring boot
程序员岳焱1 小时前
深度剖析:Spring AI 与 LangChain4j,谁才是 Java 程序员的 AI 开发利器?
java·人工智能·后端
都叫我大帅哥1 小时前
AQS(AbstractQueuedSynchronizer)深度解剖:从“奶茶店排队”到源码级设计哲学
java
斯奕sky_small-BAD1 小时前
C++ if语句完全指南:从基础到工程实践
java·开发语言·php
云之渺1 小时前
125java
java
都叫我大帅哥1 小时前
Java ReentrantLock:从“舔狗式等待”到源码级征服指南
java
程序员岳焱1 小时前
Java 高级泛型实战:8 个场景化编程技巧
java·后端·编程语言
钢铁男儿1 小时前
C# 类和继承(扩展方法)
java·servlet·c#
饮长安千年月2 小时前
JavaSec-SpringBoot框架
java·spring boot·后端·计算机网络·安全·web安全·网络安全
移动开发者1号2 小时前
Android 大文件分块上传实战:突破表单数据限制的完整方案
android·java·kotlin