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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容