题目来源【Leetcode】
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.
这道题就是返回所有左子叶值的和
/**
* 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 sumOfLeftLeaves(TreeNode* root) {
if(root == NULL)return 0;
if(root->left && !root->left->left&& !root->left->right){
return root->left->val+sumOfLeftLeaves(root->right);
}
return sumOfLeftLeaves(root->left)+sumOfLeftLeaves(root->right);
}
};

本文介绍了一道来自LeetCode的题目:计算给定二叉树中所有左叶子节点的值之和。通过递归遍历的方法解决该问题,并给出了具体的C++实现代码。
781

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



