Created
August 24, 2020 16:42
-
-
Save lishunan246/a7e884a1e878b303268413bb0f1985b5 to your computer and use it in GitHub Desktop.
Sum of Left Leaves
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode() : val(0), left(nullptr), right(nullptr) {} | |
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} | |
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} | |
* }; | |
*/ | |
int s(TreeNode* root) { | |
int sum = 0; | |
if (root->left) { | |
if (root->left->left == nullptr && root->left->right == nullptr) { | |
sum += root->left->val; | |
} | |
else { | |
sum += s(root->left); | |
} | |
} | |
if (root->right) { | |
sum += s(root->right); | |
} | |
return sum; | |
} | |
class Solution { | |
public: | |
int sumOfLeftLeaves(TreeNode* root) { | |
if (root == nullptr) { | |
return 0; | |
} | |
return s(root); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment