Created
April 25, 2022 16:21
-
-
Save perjerz/dd2024a34779cdd48cb23debc0f9102d to your computer and use it in GitHub Desktop.
Sum of Left Leaves - LeetCode
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
// 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