https://leetcode-cn.com/problems/sum-of-left-leaves/
计算给定二叉树的所有左叶子之和。
示例:
3
/
9 20
/
15 7
在这个二叉树中,有两个左叶子,分别是 9 和 15,所以返回 24
思路: 递归遍历二叉树
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int find_left_sum(int sum, bool left, struct TreeNode* root){
if(root->left == NULL && root->right == NULL && left == true){
return sum + root->val;
}
int ret1 = 0;
int ret2 = 0;
if(NULL != root->left){
ret1 = find_left_sum(sum, true, root->left);
}
if(NULL != root->right){
ret2 = find_left_sum(sum, false, root->right);
}
return ret1 + ret2;
}
int sumOfLeftLeaves(struct TreeNode* root) {
if(NULL == root){
return 0;
}
bool left = false;
return find_left_sum(0, false, root);
}