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;
    }
}
相关推荐
zzb15806 小时前
RAG from Scratch-优化-query
java·数据库·人工智能·后端·spring·mybatis
wuqingshun3141596 小时前
如何停止一个正在退出的线程
java·开发语言·jvm
Eward-an7 小时前
【算法竞赛/大厂面试】盛最多水容器的最大面积解析
python·算法·leetcode·面试·职场和发展
阿豪学编程7 小时前
LeetCode438: 字符串中所有字母异位词
算法·leetcode
Trouvaille ~7 小时前
【递归、搜索与回溯】专题(七):FloodFill 算法——勇往直前的洪水灌溉
c++·算法·leetcode·青少年编程·面试·蓝桥杯·递归搜索回溯
Barkamin7 小时前
队列的实现(Java)
java·开发语言
Storynone7 小时前
【Day23】LeetCode:455. 分发饼干,376. 摆动序列,53. 最大子序和
python·算法·leetcode
骇客野人8 小时前
自己手搓磁盘清理工具(JAVA版)
java·开发语言
J2虾虾8 小时前
在SpringBoot中使用Druid
java·spring boot·后端·druid
清风徐来QCQ8 小时前
Java笔试总结一
java·开发语言