404. Sum of Left Leaves

Easy
第一check根结点的左节点是不是左叶子节点,是的话就加到res里面,不是的话就对根结点的左子树recursively call sumOfLeftLeaves,一直递归到root.left就是左叶子节点加到res里; 左边看完了对根结点的右子树直接recursively call 这个function,也比较好理解,就是把右子树完全看成一棵树求它的左叶子节点和。其实这里的base case就是root.left 是leave left node这种情况。

/**
 * 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) {
        int res = 0;
        if (root == null){
            return res;
        }
        if (root.left != null && root.left.left == null && root.left.right == null){
            res += root.left.val;
        } else {
            res += sumOfLeftLeaves(root.left);
        }
        res += sumOfLeftLeaves(root.right);
        return res;
    }
}

你可能感兴趣的:(404. Sum of Left Leaves)