玩命加载中 . . .

404-左叶子之和


LeetCode 404. Sum of Left Leaves

LeetCode-404

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;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录