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;
    }
}
相关推荐
彭于晏Yan6 分钟前
LangChain4j实战三:图像模型
java·spring boot·后端·langchain
Trouvaille ~18 分钟前
【动态规划篇】专题(二):路径问题——在网格图中的决策艺术
c++·算法·leetcode·青少年编程·动态规划
SimonKing20 分钟前
跨越数据孤岛!SpringBoot使用JDBC调用Calcite联邦查询实战
java·后端·程序员
好家伙VCC28 分钟前
# 发散创新:基于Python的TTS语音合成实战与优化策略 在人工智能加速落地的今天,**文本转
java·开发语言·人工智能·python
等D春C夏X1 小时前
最终版C++11/14/17学习大纲(精准核对42条条款)
java·开发语言
Cg136269159741 小时前
HTML标题标签
java
feathered-feathered1 小时前
测试实战【用例设计】自己写的项目+功能测试(1)
java·服务器·后端·功能测试·jmeter·单元测试·压力测试
洋洋技术笔记1 小时前
Spring Boot自动装配原理
java·spring boot
iameyama1 小时前
Amazon Redshift 和 BigQuery 数据类型区别
java·开发语言