Java | Leetcode Java题解之第404题左叶子之和

题目:

题解:

java 复制代码
class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        }

        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.offer(root);
        int ans = 0;
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node.left != null) {
                if (isLeafNode(node.left)) {
                    ans += node.left.val;
                } else {
                    queue.offer(node.left);
                }
            }
            if (node.right != null) {
                if (!isLeafNode(node.right)) {
                    queue.offer(node.right);
                }
            }
        }
        return ans;
    }

    public boolean isLeafNode(TreeNode node) {
        return node.left == null && node.right == null;
    }
}
相关推荐
CodeStats4 分钟前
【Linux IO】从文件描述符到硬件中断:Linux IO 系统底层完全拆解
java·linux·开发语言·io·socket
大阿明9 分钟前
C++智能指针与RAII机制精讲:彻底根治内存泄漏与野指针
java·jvm·c++
一生了无挂12 分钟前
C++面向对象核心精讲:类、对象、封装、权限与生命周期全解析
java·jvm·c++
她说..15 分钟前
Apache Commons Lang3 Pair 完整版实战详解
java·spring·java-ee·apache·springboot
砍材农夫23 分钟前
redis|spring-boot redis geo|附近定位功能
java·spring boot·redis
满怀冰雪42 分钟前
第29篇-状态压缩DP-当状态很多时如何降维优化
java·算法·动态规划
weixin_4467291644 分钟前
javaweb--文件上传
java
令狐掌门1 小时前
2026华为OD面试题020:日志文件异常检测
算法·leetcode·华为od
渡我白衣1 小时前
打印宏与socket模块设计
java·linux·开发语言·c++·ide·人工智能·eclipse
智码看视界1 小时前
Day18 SpringBoot自动配置原理:从@SpringBootApplication开始
java·spring boot·后端·自动装配