Skip to content

Instantly share code, notes, and snippets.

@perjerz
Created April 25, 2022 16:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save perjerz/dd2024a34779cdd48cb23debc0f9102d to your computer and use it in GitHub Desktop.
Save perjerz/dd2024a34779cdd48cb23debc0f9102d to your computer and use it in GitHub Desktop.
Sum of Left Leaves - LeetCode
// https://leetcode.com/problems/sum-of-left-leaves/
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {number}
*/
var isLeafNode = function(node) {
if (!node) {
return false;
}
if (node.left || node.right) {
return false;
}
return true;
}
var sumOfLeftLeaves = function(root) {
let sum = 0;
if (root) {
if (isLeafNode(root.left)) { // leaf node
sum += root.left.val;
} else {
sum += sumOfLeftLeaves(root.left);
}
sum += sumOfLeftLeaves(root.right);
}
return sum;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment