LeetCode404_404. The sum of the left leaves

LeetCode404_404. The sum of the left leaves

1. Description

Given the root node root of a binary tree, return the sum of all left leaves.

Example 1:

insert image description here

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

Example 2:

输入: root = [1]
输出: 0

hint:

The number of nodes is in the range [1, 1000]
-1000 <= Node.val <= 1000

Two, solution

Method 1: Recursion

    //AC Your runtime beats 99.90 % of java submissions.
    //102 / 102 test cases passed.	Status: Accepted	Runtime: 8 ms
    public int sumOfLeftLeaves(TreeNode root) {
    
    
        if (root == null) return 0;
        if (root.left != null && root.left.left == null && root.left.right == null)
            return root.left.val + sumOfLeftLeaves(root.right);
        return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
    }

LeetCode 367. Valid Perfect Squares
LeetCode 371. Sum of Two Integers
LeetCode 383. Ransom Letter LeetCode
387. First Unique Character in a String
LeetCode 389. Find Differences
LeetCode 404. Sum of Left Leafs
LeetCode 412. Fizz Buzz
LeetCode 414. Third Largest Number
LeetCode 415. Adding Strings
LeetCode 434. Number of Words in a String



Disclaimer:
        The copyright of the topic belongs to the original author. The code and related statements in the article are written by myself based on my understanding. The relevant pictures in the article are screenshots from my own practice and pictures corresponding to related technologies. If you have any objections, please contact to delete them. grateful. Reprint please indicate the source, thank you.


By luoyepiaoxue2014

Station B: https://space.bilibili.com/1523287361 Click to open the link
Weibo: http://weibo.com/luoyepiaoxue2014 Click to open the link

Guess you like

Origin blog.csdn.net/luoyepiaoxue2014/article/details/129992808