/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int sum(TreeNode *root ,bool left)
{
if(root==NULL)return 0;
if(root->left==NULL&&root->right==NULL&&left)return root->val;
else return sum(root->left,true)+sum(root->right,false);
}
int sumOfLeftLeaves(TreeNode* root) {
return sum(root,false);
}
};
左叶之和
本文介绍了一个C++实现的算法,该算法用于计算给定二叉树中所有左叶子节点的和。通过递归遍历二叉树,当遇到左叶子节点时将其值累加到总和中。该算法简洁高效,易于理解和实现。
781

被折叠的 条评论
为什么被折叠?



