题目描述:
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.
class Solution {
public:
int sumOfLeftLeaves(TreeNode* root) {
int sum=0;
if(root==NULL) return sum;
if(root->left!=NULL) visit_leaves(root->left,sum,true);
if(root->right!=NULL) visit_leaves(root->right,sum,false);
return sum;
}
void visit_leaves(TreeNode* root, int& sum, bool isLeft)
{
if(root==NULL) return;
if(isLeft&&root->left==NULL&&root->right==NULL) sum+=root->val;
if(root->left!=NULL) visit_leaves(root->left,sum,true);
if(root->right!=NULL) visit_leaves(root->right,sum,false);
}
};
本文介绍了一个计算给定二叉树中所有左叶子节点值之和的方法。通过递归遍历二叉树,当遇到左叶子节点时将其值累加到总和中。该算法使用C++实现,并提供了完整的代码示例。
412

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



