LeetCode 404. Sum of Left Leaves

LeetCode 404. Sum of Left Leaves (左叶子之和)

题目

链接

问题描述

给定二叉树的根节点 root ,返回所有左叶子之和。

示例

输入: root = [3,9,20,null,null,15,7]
输出: 24
解释: 在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24

提示

节点数在 [1, 1000] 范围内
-1000 <= Node.val <= 1000

思路

可以说是遍历完所有节点就可以得出结果。

对于每个结点,先判断是否为空,为空不需考虑。不为空则判断是否为左叶子,是就加起来,不是就向下。

复杂度分析

时间复杂度 O(n)
空间复杂度 O(n)

代码

Java

    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) {
            return 0;
        } else {
            int sum = sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
            if (root.left != null && root.left.left == null && root.left.right == null) {
                sum += root.left.val;
            }
            return sum;
        }
    }
posted @ 2022-06-03 09:45  cheng102e  阅读(11)  评论(0编辑  收藏  举报