Skip to content
本页目录

0404-左叶子之和

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

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

示例 1:

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

示例 2:

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

提示:

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

思路

统计左叶子之和,就是分别统计左子树的左叶子之和 + 右子树的左叶子之和,再相加 需要注意左叶子的有效判断,应该 root.left != null 且 root.left 的子节点都为空

参考代码

csharp
public class Solution {
    public int SumOfLeftLeaves(TreeNode root) {
    	if(root == null){
    		return 0;
    	}
        int left = 0;
    	if(root.left != null &&  root.left.left == null && root.left.right == null){
    		left = root.left.val;
    	}
        else{
            left = SumOfLeftLeaves(root.left);
        }
    	int right = SumOfLeftLeaves(root.right);
    	return left + right;
    }
}

Released under the MIT License.