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;
    }
}
相关推荐
逆境不可逃2 小时前
LeetCode 热题 100 之 394. 字符串解码 739. 每日温度 84. 柱状图中的最大矩形
算法·leetcode·职场和发展
重生之后端学习3 小时前
62. 不同路径
开发语言·数据结构·算法·leetcode·职场和发展·深度优先
冬夜戏雪3 小时前
实习面经摘录(六)
java
big_rabbit05023 小时前
[算法][力扣283]Move Zeros
算法·leetcode·职场和发展
把你毕设抢过来3 小时前
基于Spring Boot的演唱会购票系统的设计与实现(源码+文档)
java·spring boot·后端
⑩-3 小时前
Redis内存淘汰策略?如何处理大Key?
java·数据库·redis
淡泊if3 小时前
eBPF 实战:一次诡异的 Nginx 高延迟,我用 5 分钟在内核里找到了真凶
java·运维·nginx·微服务·ebpf
重生之后端学习3 小时前
64. 最小路径和
数据结构·算法·leetcode·排序算法·深度优先·图论
李白的粉3 小时前
基于springboot的桂林旅游景点导游平台
java·spring boot·毕业设计·课程设计·源代码·桂林旅游景点导游平台
毕设源码-赖学姐3 小时前
【开题答辩全过程】以 花卉交易系统为例,包含答辩的问题和答案
java