LeetCode-Sum_of_Left_Leaves

这是一篇关于求解给定二叉树中所有左叶子节点之和的博客。通过递归方法,当遇到左子节点为叶子节点时,累加其值。文章提供了C++实现代码。

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

题目:

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.


翻译:

给定一棵二叉树,找到所有左叶子的和。

例子:

  3
   / \
  9  20
    /  \
   15   7

二叉树中有两个左叶子,它们的值分别为9和15。返回24。


思路:

递归,注意边界:

if((root->left!=NULL)&&(root->left->right==NULL)&&(root->left->left==NULL))
sum = root->left->val;

C++代码(Visual Studio 2017):

#include "stdafx.h"
#include <iostream>
using namespace std;

struct TreeNode {
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode(int x) :val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
	int sumOfLeftLeaves(TreeNode* root) {
		if (root == NULL) 
			return 0;
		int sum = 0;
		if((root->left!=NULL)&&(root->left->right==NULL)&&(root->left->left==NULL))
			sum = root->left->val;
		return sum + sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);
	}
};

int main()
{
	Solution s;
	TreeNode* root = new TreeNode(3);
	root->left = new TreeNode(9);
	root->right = new TreeNode(20);
	root->right->left = new TreeNode(15);
	root->right->right = new TreeNode(7);
	int result;
	result = s.sumOfLeftLeaves(root);
	cout << result;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值