代码随想录——左叶子之和(Leetcode404)

题目链接

BFS + 队列

java 复制代码
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public int sumOfLeftLeaves(TreeNode root) {
        int sum = 0;
        Deque<TreeNode> queue = new LinkedList<TreeNode>();
        if(root == null){
            return sum;
        }
        queue.offer(root);
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i = 0; i < size; i++){
                TreeNode node = queue.poll();
                if(node.left != null){
                    queue.offer(node.left);
                    // 注意题目要求是求左叶子之和,所以需要判断一下左节点是否为叶子节点
                    if(node.left.left == null && node.left.right == null){
                        sum += node.left.val;
                    }
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
            }
        }
        return sum;
    }
}
相关推荐
兮动人15 小时前
Java 单元测试中的 Mockito 使用详解与实战指南
java·开发语言·单元测试
豆沙沙包?15 小时前
2025年--Lc186--64. 最小路径和(多维动态规划,矩阵)--Java版
java·矩阵·动态规划
武子康15 小时前
Java-151 深入浅出 MongoDB 索引详解 性能优化:慢查询分析 索引调优 快速定位并解决慢查询
java·开发语言·数据库·sql·mongodb·性能优化·nosql
程序猿Eason15 小时前
U587038 背包 题解
c++·算法·动态规划
Query*15 小时前
Java 设计模式——建造者模式:从原理到实战的极简指南
java·设计模式·建造者模式
potato_may16 小时前
第18讲:C语言内存函数
c语言·数据结构·算法
zl97989916 小时前
SpringBoot-入门介绍
java·spring boot·spring
焰火199916 小时前
[Java]基于Redis的分布式环境下的自增编号生成器
java·后端
ZhengEnCi16 小时前
JPA-SQL 语句使用完全指南-自动生成vs手动编写的智能选择策略
java·spring boot·sql
毕设源码-钟学长16 小时前
【开题答辩全过程】以 菜谱分享平台为例,包含答辩的问题和答案
java·eclipse