首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >LeetCode404. Sum of Left Leaves所有左叶节点的和 #算法# 第十四周

LeetCode404. Sum of Left Leaves所有左叶节点的和 #算法# 第十四周

作者头像
梦飞
发布于 2022-06-23 11:26:39
发布于 2022-06-23 11:26:39
2860
举报
文章被收录于专栏:csdn文章同步csdn文章同步

原题

Find the sum of all left leaves in a given binary tree.

Example:

代码语言:javascript
复制
    3
   / \
  9  20
    /  \
   15   7

There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.

思路

可以用递归的思想, (1)若节点为空,则为0; (2)若左子节点为叶子节点,则加上其值,否则加上左子节点的所有左叶节点的和 (3)再加上右子节点的所有左叶子节点的和

代码

代码语言:javascript
复制
class Solution {
public:
    int sumOfLeftLeaves(TreeNode* root) {
        if(root == NULL) return 0;
        int ans = 0;
        if(root->left != NULL){
            if(root->left->left == NULL && root->left->right == NULL)
                ans += root->left->val;
            else
                ans += sumOfLeftLeaves(root->left);
        }
        ans += sumOfLeftLeaves(root->right);
        return ans;
    }
};
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-12-09,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 原题
  • 思路
  • 代码
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档