JesseZhao1990/algorithm

左叶子之和

JesseZhao1990 opened this issue · 0 comments

image

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {number}
 */
var sumOfLeftLeaves = function(root) {
    if(root === null) return 0;
    if(root.left !== null){
        if(root.left.left === null && root.left.right ===null){
            return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right) + root.left.val;
        }
    };
    return sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
};

解题思路:递归遍历每个节点,当节点的右子树是叶子节点时,捡起此节点的值

leetcode 原题地址:https://leetcode-cn.com/problems/sum-of-left-leaves/description/