Home | Projects | Notes > Problem Solving > LC - E - 404. Sum of Left Leaves (DFS)
This solution uses Depth-First Search (DFS) algorithm.
The strategy is to perform DFS and accumulate the values of the left leaves only.
Complexity Analysis:
Solution:
xxxxxxxxxx381/**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode() : val(0), left(nullptr), right(nullptr) {}8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}10 * };11 */12class Solution {13public:14 int sumOfLeftLeaves(TreeNode* root) {15 int sum = 0;16 helper(root, sum, 0);17 return sum;18 }19
20private:21 void helper(TreeNode *curr, int &sum, bool isLeft)22 {23 // terminating condition 124 if (curr == nullptr)25 return;26
27 // terminating condition 228 if (curr->left == curr->right)29 {30 sum += (curr->val * isLeft);31 return;32 }33 34 // recursive step35 helper(curr->left, sum, 1);36 helper(curr->right, sum, 0);37 }38};
This solution does not use helper function or additional variable.
Complexity Analysis:
Solution:
xxxxxxxxxx251/**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode() : val(0), left(nullptr), right(nullptr) {}8 * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}9 * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}10 * };11 */12class Solution {13public:14 int sumOfLeftLeaves(TreeNode* root) {15 if (!root)16 return 0;17
18 // if left node is a leaf19 if (root->left && !root->left->left && !root->left->right)20 return root->left->val + sumOfLeftLeaves(root->right);21 22 // otherwise23 return sumOfLeftLeaves(root->left) + sumOfLeftLeaves(root->right);24 }25};