404. Sum of Left Leaves
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
题意
找到二叉树中所有左叶子结点的和
思路
递归!左子树中左叶子结点的和+右子树中右叶子结点的和
递归的终止条件
代码
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
if (!root) return 0;
//当前结点的左结点是叶子结点,获取左结点的值
//并且看当前结点的右结点是否满足
//相当于边界条件有两条
if (root->left && !root->left->left && !root->left->right)
{
return root->left->val + sumOfLeftLeaves(root->right);
}
//找左子树中左叶子结点的和
//看右结点
int leftSum = sumOfLeftLeaves(root->lchild);
int rightSum = sumOfLeftLeaves(root->rchild);
return leftSum + rightSum;
}
};