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 分钟前
【Java从入门到入土】21:List三剑客:ArrayList、LinkedList、Vector的爱恨情仇
java·javascript·网络·python·list
AlenTech5 分钟前
139. 单词拆分 - 力扣(LeetCode)
算法·leetcode·职场和发展
SAP小崔说事儿10 分钟前
SAP B1 批量应用用户界面配置模板
java·前端·ui·sap·b1·无锡sap
电商API&Tina20 分钟前
唯品会数据采集API接口||电商API数据采集
java·javascript·数据库·python·sql·json
人机与认知实验室25 分钟前
Maven与以色列福音系统有何区别?
java·maven
wuqingshun31415926 分钟前
spring如何解决循环依赖问题的?
java
凸头1 小时前
SpringDoc OpenAPI 泛型返回值完美解决方案
java
Predestination王瀞潞1 小时前
Java EE3-我独自整合(第一章:Spring入门)
java·spring·java-ee