404. Sum of Left Leaves

本文介绍了一种计算给定二叉树中所有左叶子结点值之和的方法。通过递归遍历二叉树,标记左孩子并判断是否为叶子结点,最终返回所有符合条件的左叶子结点值总和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

404. Sum of Left Leaves

1. 题目

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.

2. 题解:

  • 解题思路: 递归函数中借助一个变量来标记左右孩子。如果为左孩子,且为叶子结点,则加上此节点的值;如果有节点存在,则遍历右子树
  • 代码实现:
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
#define RIGHT_CHILD 0
#define LEFT_CHILD  1
int sumOfLeftLeavesRecursion(struct TreeNode* root, int child){
    if(NULL == root){
        return 0;
    }
    if(NULL == root->left && NULL == root->right && LEFT_CHILD == child)
        return root->val;
    
    return sumOfLeftLeavesRecursion(root->left, LEFT_CHILD) + sumOfLeftLeavesRecursion(root->right, RIGHT_CHILD); 
}


int sumOfLeftLeaves(struct TreeNode* root){
    if(NULL == root){
        return 0;
    }
    return sumOfLeftLeavesRecursion(root, RIGHT_CHILD);/*根节点需要输出吗???  leetcode结果显示不需要*/
}
  • 提交结果:

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

叨陪鲤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值