Description
Find the sum of all left leaves in a given binary tree.
Example:
3
/ \
9 20
/ \
15 7There are two left leaves in the binary tree, with values 9 and 15 respectively. Return 24.
Analysis
Simply use a bool variable to mark whether the node is a left or right child of its father node. In my code, true represents left, while false represents right.
Code
/**
* 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) return 0;
sum = 0;
find(root,false);
return sum;
}
private:
int sum;
void find(TreeNode* t, bool flag){
if (t->left) find(t->left,true);
if (t->right) find(t->right,false);
if (!t->left && !t->right && flag) sum += t->val;
}
};
Appendix
- Link: https://leetcode.com/problems/sum-of-left-leaves/
- Run Time: 3ms