Problem Description could be found @https://leetcode.com/problems/sum-of-left-leaves/
Solution
class Solution {
public:
int helper(TreeNode* root, TreeNode *parent){
if (root->left == NULL && root->right == NULL && root == parent->left ){
return root->val;
}
int rightVal = 0;
int leftVal = 0;
if (root->left != NULL)
leftVal = helper(root->left, root);
if ( root->right != NULL)
rightVal = helper(root->right, root);
return (leftVal + rightVal);
}
int sumOfLeftLeaves(TreeNode* root) {
if (root == NULL )
return 0;
if (root->left == NULL && root->right == NULL)
return 0;
int num = helper(root, NULL);
return num;
}
};
Solution
class Solution {
public:
int helper(TreeNode* root, TreeNode *parent){
if (root->left == NULL && root->right == NULL && root == parent->left ){
return root->val;
}
int rightVal = 0;
int leftVal = 0;
if (root->left != NULL)
leftVal = helper(root->left, root);
if ( root->right != NULL)
rightVal = helper(root->right, root);
return (leftVal + rightVal);
}
int sumOfLeftLeaves(TreeNode* root) {
if (root == NULL )
return 0;
if (root->left == NULL && root->right == NULL)
return 0;
int num = helper(root, NULL);
return num;
}
};
No comments:
Post a Comment