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;
    }
}
相关推荐
文丑颜不良啊5 小时前
LeetCode2981~3000题目解析
java·leetcode
nice_lcj5207 小时前
【从零理解 Spring AI · 13】RAG 要解决什么:把“闭卷考试“变成“开卷“
java·spring·检索增强·rag·spring ai·ai应用开发
学长毕设7 小时前
基于SpringBoot军事纪念馆管理系统设计与实现-附源码
java·spring boot·后端
这个昵称不容易8 小时前
SpringBoot 医疗病历交互系统的设计与实现:192 个 Java 文件、256 个接口、22 张表,附真实运行截图
java·springboot·毕设
驭渊的小故事9 小时前
订单服务如何调用商品服务?一次 RestTemplate 跨服务调用入门
java·开发语言·php
文丑颜不良啊11 小时前
LeetCode3001~3020题目解析
java·leetcode
山楂树の12 小时前
Java 字符串高效处理:StringBuilder、StringBuffer、StringJoiner
java·开发语言
.痞老板.14 小时前
java ee--文件操作和IO
java·java-ee
简 洁 冬冬14 小时前
分页「向上取整」公式 `(total + size - 1) / size` 的完整推导
java·分页
装不满的克莱因瓶16 小时前
【从零搭建】AI大模型之ReactAgent智能体对接MCP实战
java·人工智能·ai·springai·mcp·springaialibaba