404. Sum of Left Leaves

404. Sum of Left Leaves_第1张图片

C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
       if(root==NULL) return 0;
        else if(root->left!=NULL&&root->left->left==NULL&&root->left->right==NULL)
        {
        return  sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right)+root->left->val;
        }
        else 
        return sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right)+0;
    }
};

Java

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

Javascript

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

最优解,一样

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