题目描述

Find the sum of all left leaves in a given binary tree.

Example:

``````    3
/ \
9  20
/  \
15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.``````

解法一

思路

``````def sumOfLeftLeaves(root):
...
sum = self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
# TODO
return sum``````

``````if root.left and root.left.left is None and root.left.right is None:
# TODO``````

Python

``````# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution(object):
def sumOfLeftLeaves(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root is None:
return 0
sum = self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)
if root.left and root.left.left is None and root.left.right is None:
sum += root.left.val
return sum``````

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;
}
int sum = sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right);
if (root.left != null && root.left.left == null && root.left.right == null) {
sum += root.left.val;
}
return sum;
}
}``````

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 == nullptr) {
return 0;
}
int sum = sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
if (root->left && root->left->left == nullptr && root->left->right == nullptr) {
sum += root->left->val;
}
return sum;
}
};``````