LeetCode 404. Sum of Left Leaves
Given the root of a binary tree, return the sum of all left leaves.
Example 1:
Input: root = [3,9,20,null,null,15,7]
Output: 24
Explanation: There are two left leaves in the binary tree, with values 9 and 15 respectively.
method: 递归
左叶子的判断:当前节点的左节点不为空,左节点的左节点和右节点为空
- 递归计算左右子树的结果
- 如果当前节点满足右节点是叶子节点的条件,就加上,没有就算了
int sumOfLeftLeaves(TreeNode* root) {
if (!root) return 0;
int leftSum = sumOfLeftLeaves(root->left);
int rightSum = sumOfLeftLeaves(root->right);
int midSum = 0; // 算当前点的结果
if (root->left && !root->left->left && !root->left->right)
midSum = root->left->val;
return midSum + leftSum + rightSum;
}