Sum of Left Leaves Solutions in C++
Number 404
Difficulty Easy
Acceptance 51.0%
Link LeetCode
Solutions
C++ solution by haoel/leetcode
// Source : https://leetcode.com/problems/sum-of-left-leaves/// Author : Hao Chen// Date : 2016-11-12/*** 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:void sumOfLeftLeaves_recursion_v1(TreeNode* root, int& result) {if (root == NULL ) {return;}if (root->left && root->left->left == NULL && root->left->right == NULL) {result += root->left->val;}sumOfLeftLeaves_recursion_v1(root->left, result);sumOfLeftLeaves_recursion_v1(root->right, result);}int sumOfLeftLeaves_recursion_v2(TreeNode* root) {if (root == NULL ) {return 0;}int result = 0;if (root->left && root->left->left == NULL && root->left->right == NULL) {result = root->left->val;}result += sumOfLeftLeaves_recursion_v2(root->left) + sumOfLeftLeaves_recursion_v2(root->right);return result;}int sumOfLeftLeaves(TreeNode* root) {srand(time(NULL));if (rand()%2) {int result = 0;sumOfLeftLeaves_recursion_v1(root, result);return result;} else {return sumOfLeftLeaves_recursion_v2(root);}}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/sum-of-left-leaves//// Author : liuyubobobo/// Time : 2019-04-22#include <iostream>using namespace std;/// Recursion/// Time Complexity: O(n)/// Space Complexity: O(h)/// 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 {private:int res = 0;public:int sumOfLeftLeaves(TreeNode* root) {if(!root) return 0;dfs(root, false);return res;}private:void dfs(TreeNode* node, bool isLeft){if(!node->left && !node->right){if(isLeft) res += node->val;return;}if(node->left) dfs(node->left, true);if(node->right) dfs(node->right, false);}};int main() {return 0;}
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/sum-of-left-leaves//// Author : liuyubobobo/// Time : 2019-04-22#include <iostream>using namespace std;/// Recursion/// Don't use class member variable/// Time Complexity: O(n)/// Space Complexity: O(h)/// 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;return dfs(root, false);}private:int dfs(TreeNode* node, bool isLeft){if(!node->left && !node->right){if(isLeft) return node->val;return 0;}int res = 0;if(node->left) res += dfs(node->left, true);if(node->right) res += dfs(node->right, false);return res;}};int main() {return 0;}