LeetCode 404 Sum of Left Leaves

本文介绍了一种算法,用于计算给定二叉树中所有左子叶节点的值之和。通过递归方式遍历二叉树,实现了两种解决方案:一是通过辅助函数区分左右子树并累加左子叶的值;二是直接在主函数内完成递归逻辑。

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

Problem:

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

Summary:

求左子叶之和。

Analysis:

1. 求左子叶之和,即需要遍历整棵二叉树,常规的方法则为递归。首先我想到的是调用子函数,在子函数中递归,每递归至一个新的节点,首先传入bool类型标记是根节点的左子树还是右子树。若为左子树,且为叶子节点,则将当前节点的value计入和中。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int sumOfLeftLeaves(TreeNode* root) {
13         if (root == NULL) {
14             return 0;
15         }
16         
17         int sum = 0;
18         calLeftLeaves(root->left, true, sum);
19         calLeftLeaves(root->right, false, sum);
20         
21         return sum;
22     }
23 
24 private:
25     void calLeftLeaves(TreeNode* root, bool left, int& sum) {
26         if (root == NULL) {
27             return;
28         }
29         
30         if (left && (root->left == NULL) && (root->right == NULL)) {
31             sum += root->val;
32         }
33         
34         calLeftLeaves(root->left, true, sum);
35         calLeftLeaves(root->right, false, sum);
36     }
37 };

 2. 进一步简化代码,试图不掉用子函数,在主函数中进行递归操作。

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int sumOfLeftLeaves(TreeNode* root) {
13         if (root == NULL) {
14             return 0;
15         }
16         
17         if (root->left && root->left->left == NULL && root->left->right == NULL) {
18             return root->left->val + sumOfLeftLeaves(root->right);
19         }
20         
21         return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);
22     }
23 };

 

转载于:https://www.cnblogs.com/VickyWang/p/5998855.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值