404. Sum of Left Leaves

本文介绍了一种计算给定二叉树中所有左叶子结点值之和的方法,通过深度优先搜索(DFS)、广度优先搜索(BFS)及递归三种不同算法实现。

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

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.

来自 <https://leetcode.com/problems/sum-of-left-leaves/description/> 

2.问题分析

找出所有的左叶子结点,并求和,同样是用深度优先遍历方式,比较简单。

2.C++代码

//我的代码:(beats 94%)
//DFS
int sumOfLeftLeaves(TreeNode* p)
{
    if (p == NULL)
        return 0;
    int sum = 0; 
    stack<TreeNode*>s;
    while (!s.empty() || p != NULL)
    {
        while (p)
        {
            s.push(p);
            p = p->left;
        }
        if (!s.empty())
        {
            p = s.top();
            s.pop();
            if (p->left&&p->left->left == NULL&&p->left->right == NULL)//左叶子
            {
                sum += p->left->val;
                cout<< p->left->val<<endl;
            }
            p = p->right;
        }
    }
    return sum;
}

既然DFS可以,那么BFS也可以

//BFS
int sumOfLeftLeaves2(TreeNode* p)
{
    if (p == NULL)
        return 0;
    int sum = 0;
    queue<TreeNode*> q;
    q.push(p);
    while (!q.empty())
    {
        TreeNode *tmp = q.front();
        q.pop();
        if (tmp->left)
        {
            q.push(tmp->left);
            if (tmp->left->left == NULL&&tmp->left->right == NULL)
            {
                sum += tmp->left->val;
                cout << tmp->left->val << endl;
            }
        }   
        if (tmp->right)
            q.push(tmp->right);
    }
    return sum;
}

试试递归

//递归
int sumOfLeftLeaves(TreeNode* p)
{
    int sum = 0;
    if (p == NULL)
        return 0;
    if (p->left)
    {
        if (p->left->left == NULL&&p->left->right == NULL)
        {
            sum += p->left->val;
            cout << p->left->val << endl;;
        }
        sum += sumOfLeftLeaves(p->left);
    }   
    if(p->right)
        sum+=sumOfLeftLeaves(p->right);
    return sum;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值