首页 > 其他分享 >leetcode-404-easy

leetcode-404-easy

时间:2022-10-23 22:44:25浏览次数:54  
标签:right return sumOfLeftLeaves2 404 easy null root leetcode left

Sum of Left Leaves

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

A leaf is a node with no children. A left leaf is a leaf that is the left child of another node.

Example 1:

Input: root = [3,9,20,null,null,15,7]
Output: 24
Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.
Example 2:

Input: root = [1]
Output: 0
Constraints:

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

思路一:递归,递归的结束条件是 left Leaves 的判断条件,即没有左右两个子节点,刚开始做的时候没有仔细看题,右边的子节点也要判空

public int sumOfLeftLeaves(TreeNode root) {
    return sumOfLeftLeaves2(root.left, true) + sumOfLeftLeaves2(root.right, false);
}

public int sumOfLeftLeaves2(TreeNode root, boolean isLeft) {
    if (root == null) return 0;


    if (root.left == null && root.right == null && isLeft) {
        return root.val;
    }


    return sumOfLeftLeaves2(root.left, true) + sumOfLeftLeaves2(root.right, false);
}

标签:right,return,sumOfLeftLeaves2,404,easy,null,root,leetcode,left
From: https://www.cnblogs.com/iyiluo/p/16819880.html

相关文章