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;
    }
}
相关推荐
lUie INGA5 小时前
在2023idea中如何创建SpringBoot
java·spring boot·后端
geBR OTTE6 小时前
SpringBoot中整合ONLYOFFICE在线编辑
java·spring boot·后端
Porunarufu6 小时前
博客系统UI自动化测试报告
java
Aurorar0rua7 小时前
CS50 x 2024 Notes C - 05
java·c语言·数据结构
Cosmoshhhyyy8 小时前
《Effective Java》解读第49条:检查参数的有效性
java·开发语言
布谷歌8 小时前
常见的OOM错误 ( OutOfMemoryError全类型详解)
java·开发语言
6Hzlia8 小时前
【Hot 100 刷题计划】 LeetCode 739. 每日温度 | C++ 逆序单调栈
c++·算法·leetcode
eLIN TECE8 小时前
springboot和springframework版本依赖关系
java·spring boot·后端
老神在在0018 小时前
Spring Bean 的六种作用域详解
java·后端·spring
仙草不加料8 小时前
互联网大厂Java面试故事实录:三轮场景化技术提问与详细答案解析
java·spring boot·微服务·面试·aigc·电商·内容社区