LeetCode 左叶子之和

1.题目

在这里插入图片描述

2.思路(Java语言描述)

判断当前节点是否是左节点,若是则加上该节点的值,再递归左右子树

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    
    
    public int sumOfLeftLeaves(TreeNode root) {
    
    
        if(root == null){
    
    
            return 0;
        }
        int cnt = 0;
        if(root.left!=null && root.left.left == null && root.left.right==null){
    
    
            cnt+=root.left.val;
        }
        cnt+=sumOfLeftLeaves(root.left);
        cnt+=sumOfLeftLeaves(root.right);
        return cnt;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43967679/article/details/108761109