404. 左叶子之和

深度优先搜索

class Solution {
    public int sumOfLeftLeaves(TreeNode root) {

        if (root == null){
            return 0;
        }

        int sum = 0;

        /**
         * 如果根节点有左孩子,且左孩子是叶子节点时,记录其值
         */
        if (root.left != null && root.left.left == null && root.left.right == null){
            sum += root.left.val;
        }

        return sum + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(logn)
 */

https://leetcode-cn.com/problems/sum-of-left-leaves/

posted @ 2021-12-25 21:27  振袖秋枫问红叶  阅读(12)  评论(0)    收藏  举报