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;
    }
}
相关推荐
小马爱打代码16 小时前
Java学习笔记:注解详解
java·笔记·学习
我来变强了17 小时前
token无感刷新全流程
java·vue.js
努力学算法的蒟蒻17 小时前
day14(11.14)——leetcode面试经典150
算法·leetcode
QT 小鲜肉17 小时前
【C++基础与提高】第十一章:面向对象编程进阶——继承与多态
java·linux·开发语言·c++·笔记·qt
aerror17 小时前
将sqlite3的表转成excel表
java·sqlite·excel
仟濹17 小时前
IntelliJ IDEA 快捷键 + 实时模板
java·intellij-idea
洛_尘17 小时前
数据结构--6:优先级队列(堆)
java·数据结构
大飞哥~BigFei18 小时前
RabbitMq消费消息遇到的坑
java·rabbitmq·java-rabbitmq
隐形喷火龙18 小时前
Springboot集成OnlyOffice
java·spring boot·后端